Removing characters from strings with LINQ

前端 未结 4 1664
失恋的感觉
失恋的感觉 2021-01-17 13:07

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 character

4条回答
  •  执笔经年
    2021-01-17 13:43

    I would prefer the first form with extension methods though simplified to

    public static string Remove(this string s, IEnumerable 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.

提交回复
热议问题