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)?
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());
}
But that's pretty ugly. Ergo LINQ.
The difference that I notice in the LINQ statement is that I have to use 'select' whereas with the extension method, I don't have to.
/// <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());
}
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());
}
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.
try this for terseness
public static string Remove(this string source, IEnumerable<char> chars) {
return new String(source.Where(x => !chars.Contains(x)).ToArray());
}
EDIT
Updated to correct it removing duplicates from source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With