C#将一个List字符串与其他列表字符串的子字符串进行比较

时间:2017-04-11 11:57:49

标签: c# linq

我有两个列表

List<string> ingoreEducationKeywords= new List<string>(){"Uni", "School", "College",}; 
List<string> userEducation= new List<string>(){"MCS", "BCS", "School of Arts","College of Medicine"}; 

现在我想获得一个没有来自忽略列表的子字符串的列表。

要求清单{&#34; MCS&#34;,&#34; BCS&#34;}

4 个答案:

答案 0 :(得分:6)

这是一个用自然翻译成LINQ的方式来表达你想要的东西:

  • 您需要userEducation的商品(建议您从userEducation开始)
  • ignoreEducationKeywords none 是子字符串。
    • “无”相当于“不是任何”
    • 要检查子字符串,您可以使用Contains

这导致:

var query = userEducation
   .Where(candidate => !ignoredKeyWords.Any(ignore => candidate.Contains(ignore)));

同样的思考过程可以帮助许多其他查询。

另一种选择是创建自己的None扩展方法,假设您正在使用LINQ to Objects:

public static class Extensions
{
    public static bool None(this IEnumerable<T> source, Func<T, bool> predicate)
        => !source.Any(predicate);
}

然后你可以在没有否定的情况下重写查询:

var query = userEducation
   .Where(candidate => ignoredKeyWords.None(ignore => candidate.Contains(ignore)));

答案 1 :(得分:6)

这是一个相对简单的查询,可以使用AnyAll构建,具体取决于您的偏好:

var res = userEducation
    .Where(s => !ingoreEducationKeywords.Any(ignored => s.Contains(ignored)))
    .ToList();

var res = userEducation
    .Where(s => ingoreEducationKeywords.All(ignored => !s.Contains(ignored)))
    .ToList();

如果列表非常大,您可以使用正则表达式同时匹配所有单词来提高性能:

var regex = new Regex(
    string.Join("|", ingoreEducationKeywords.Select(Regex.Escape))
);
var res = userEducation.Where(s => !regex.IsMatch(s)).ToList();

Demo.

答案 2 :(得分:3)

您可以使用WhereAnyContains

var list = userEducation.Where(ed => !ingoreEducationKeywords.Any(ik => ed.Contains(ik)));

它会搜索userEducation中教育没有匹配的ingoreEducationKeywords中的所有出现。

答案 3 :(得分:0)

List<string> ingoreEducationKeywords = new List<string>() { "Uni", "School", "College", };
List<string> userEducation = new List<string>() { "MCS", "BCS", "School of Arts", "College of Medicine" };

var result = userEducation.Where(r => !ingoreEducationKeywords.Any(t => r.Contains(t))).ToList();