Find out if string list items startswith another item from another list

独自空忆成欢 提交于 2019-12-11 03:28:49

问题


I'd like to loop over a string list, and find out if the items from this list start with one of the item from another list.

So I have something like:

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");

回答1:


You can do that using a couple simple for each loops.

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



回答2:


If you just want a list and you'd rather not use query expressions (I don't like them myself; they just don't look like real code to me)

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:


Try this one it is working fine.

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


来源:https://stackoverflow.com/questions/22988513/find-out-if-string-list-items-startswith-another-item-from-another-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!