我正在尝试通过编写一些简单的扩展方法来刷新我的LINQ.有没有更好的方法来编写如下函数从字符串中删除给定的字符列表(使用LINQ)?
它帮助我思考LINQ首先依赖的扩展方法:
public static string Remove(this string s, IEnumerable<char> chars)
{
string removeChars = string.Concat(chars);
return new string(s.ToCharArray().Where(c => !removeChars.Contains(c)).ToArray());
}
Run Code Online (Sandbox Code Playgroud)
但那很难看.Ergo LINQ.
我在LINQ语句中注意到的差异是我必须使用'select'而使用扩展方法,我不必这样做.
/// <summary>Strip characters out of a string.</summary>
/// <param name="chars">The characters to remove.</param>
public static string Remove(this string s, IEnumerable<char> chars)
{
string removeChars = string.Concat(chars);
var stripped = from c in s.ToCharArray()
where !removeChars.Contains(c)
select c;
return new string(stripped.ToArray());
}
Run Code Online (Sandbox Code Playgroud)
所以我想知道这个(上面的最后一个片段)是否是用于完成字符删除的最简洁的LINQ语句.
Ale*_*yev 12
我更喜欢第一种形式的扩展方法,虽然简化为
public static string Remove(this string s, IEnumerable<char> chars)
{
return new string(s.Where(c => !chars.Contains(c)).ToArray());
}
Run Code Online (Sandbox Code Playgroud)
至于select关键字,它是第二种形式的强制性.该文件说什么"的查询表达式必须以select子句或group子句结束".这就是为什么我会避免使用LINQ语法糖.