【问题标题】:Determine if one of three fields has any of a list of keywords确定三个字段之一是否具有任何关键字列表
【发布时间】:2012-12-09 20:48:13
【问题描述】:

假设我们有一个模型

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

【问题讨论】:

  • 请记住用相关语言标记您的问题。我为你修好了这个,但我希望一个 2k+ 代表的用户知道如何在第一时间把它弄好。

标签: c# string list contains


【解决方案1】:
var entriesSet = new HashSet<string>(foo.Something.Split());
entriesSet.UnionWith(foo.SomethingElse.Split());
entriesSet.UnionWith(foo.AnotherThing.Split());

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

【讨论】:

    【解决方案2】:

    类似

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2011-06-26
      • 2012-01-29
      • 1970-01-01
      • 2023-03-27
      • 2014-09-17
      相关资源
      最近更新 更多