【问题标题】:Find out if string list items startswith another item from another list找出字符串列表项是否以另一个列表中的另一个项开头
【发布时间】:2014-05-24 04:30:24
【问题描述】:

我想遍历一个字符串列表,并找出这个列表中的项目是否以另一个列表中的一个项目开头。

所以我有类似的东西:

List<string> firstList = new List<string>();
firstList.Add("txt random");
firstList.Add("text ok");
List<string> keyWords = new List<string>();
keyWords.Add("txt");
keyWords.Add("Text");

【问题讨论】:

标签: c# list loops startswith


【解决方案1】:

您可以对每个循环使用几个简单的方法来做到这一点。

foreach (var t in firstList) {
    foreach (var u in keyWords) {
        if (t.StartsWith(u) {
            // Do something here.
        }
    }
}

【讨论】:

  • 这太简单了,我感觉很糟糕。谢谢你的回答:)
【解决方案2】:

如果您只想要一个列表并且不想使用查询表达式(我自己不喜欢它们;它们对我来说看起来不像真正的代码)

var matches = firstList.Where(fl => keyWords.Any(kw => fl.StartsWith(kw)));

【讨论】:

    【解决方案3】:
    from item in firstList
    from word in keyWords
    where item.StartsWith(word)
    select item
    

    【讨论】:

      【解决方案4】:

      试试这个,效果很好。

      var result = firstList.Where(x => keyWords.Any(y => x.StartsWith(y)));
      

      【讨论】:

        猜你喜欢
        • 2012-11-23
        • 2012-07-04
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 2013-09-04
        • 2020-01-08
        • 1970-01-01
        • 2018-06-06
        相关资源
        最近更新 更多