Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing characters from strings with LINQ

Tags:

c#

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)?

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.

like image 376
core Avatar asked Jan 16 '09 04:01

core


2 Answers

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.

like image 144
Alexander Prokofyev Avatar answered Sep 20 '22 23:09

Alexander Prokofyev


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

like image 40
JaredPar Avatar answered Sep 19 '22 23:09

JaredPar