确定三个字段中的一个是否包含任何关键字列表

时间:2012-12-22 15:59:41

标签: c# string list contains

假设我们有一个模型

public Foo 
{
    string Something {get;set;}
    string SomethingElse {get;set;}
    string AnotherThing {get;set;}
}

确定这些字段是否包含List中的任何字符串的最简洁方法是什么?

var foo = new Foo 
{
    Something = "If Liverpool don't beat Fulham this evening I will cry",
    SomethingElse = "I hope I have that TekPub membership for Xmas",
    AnotherThing = "I wish NCrunch was a bit cheaper"
};

var keywords = new List<string> { "Liverpool", "glosrob", "stackoverflow" };

传递foo.Something包含'利物浦'这个词。

2 个答案:

答案 0 :(得分:3)

var entriesSet = new HashSet<string>(foo.Something.Split());
entriesSet.UnionWith(foo.SomethingElse.Split());
entriesSet.UnionWith(foo.AnotherThing.Split());

if (entriesSet.Overlaps(keywords)) {
    ...
}

答案 1 :(得分:2)

这样的东西
new[] { foo.Something, foo.SomethingElse, foo.AnotherThing }.Any(s => keywords.Any(w => s.Contains(w)))