Question

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");
Was it helpful?

Solution

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.
        }
    }
}

OTHER TIPS

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)));
from item in firstList
from word in keyWords
where item.StartsWith(word)
select item

Try this one it is working fine.

var result = firstList.Where(x => keyWords.Any(y => x.StartsWith(y)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top