我如何使用LINQ从各种子字符串开始过滤掉字符串?

时间:2013-04-06 13:15:30

标签: c# .net linq

假设我有var lines = IEnumerable<string>lines包含各种行,其前1..n字符将其排除在进程之外。例如,以'*','E.g。','Sample'等开头的行

排除令牌列表是可变的,仅在运行时才知道,所以

lines.Where(l => !l.StartsWith("*") && !l.StartsWith("E.g.") && ...

变得有些问题。

我怎么能实现这个目标?

2 个答案:

答案 0 :(得分:8)

使用LINQ:

 List<string> exceptions = new List<string>() { "AA", "EE" };

 List<string> lines = new List<string>() { "Hello", "AAHello", "BHello", "EEHello" };

 var result = lines.Where(x => !exceptions.Any(e => x.StartsWith(e))).ToList();
 // Returns only "Hello", "BHello"

答案 1 :(得分:2)

试试这个:

List<string> lines = new List<string>();    //add some values
List<string> exclusion=new List<string>();  //add some values

var result = lines.Except(exclusion, new MyComparer());

其中:

public class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y) { return x.StartsWith(y); }

    public int GetHashCode(string obj) { //some code }
}