使用LINQ从字符串中删除字符 [英] Removing characters from strings with LINQ
问题描述
我正在尝试通过编写一些简单的扩展方法来完善我的LINQ.有没有更好的方法来编写如下所示的函数(使用LINQ)从字符串中删除给定的字符列表?
I'm trying to brush up on my LINQ by writing some simple extension methods. Is there any better way to write such a function as below that removes a given list of characters from a string (using LINQ)?
这有助于我想到LINQ首先依赖的扩展方法:
It helps me to think of the extension methods that LINQ relies on first:
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());
}
但这很丑陋. Ergo LINQ.
But that's pretty ugly. Ergo LINQ.
我在LINQ语句中注意到的差异是我必须使用选择",而使用扩展方法则不必.
/// <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());
}
所以我想知道这(上面的最后一个片段)是否是完成字符删除的最有趣的LINQ语句.
So I'm wondering if this (last snippet above) is the tersest LINQ statement to accomplish removal of characters.
推荐答案
我希望第一种具有扩展方法的形式虽然简化为
I would prefer the first form with extension methods though simplified to
public static string Remove(this string s, IEnumerable<char> chars)
{
return new string(s.Where(c => !chars.Contains(c)).ToArray());
}
对于 select 关键字,它是第二种形式的必填项. 文档表示查询表达式必须以select子句终止或组子句".这就是为什么我会避免使用LINQ语法糖.
As for select keyword, it's obligatory in second form. The documentation says what "A query expression must terminate with either a select clause or a group clause". That's why I would avoid LINQ syntactic sugar.
这篇关于使用LINQ从字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!