0
votes

I have a list of strings that I need to find/verify in another list of strings and return those that are found.

List<string> strList1 = new List<string>() { "oranges", "apples", "grapes" };
List<string> strList2 = new List<string>() {
   "Joe likes peaches",
   "Mack likes apples",
   "Hank likes raisins",
   "Jodi likes grapes",
   "Susan likes apples"  
};

OK, so this is a bad example but, basically, I want to be able to create a Linq call to find any value in strList1 in one or more elements in strList2 and return which ones were found.

So the results would be a list of strList1 items found in ````strList2```. Something like:

List<string> found = { "apples", "grapes" };

My searching hasn't resulted in anything because I'm probably not searching correctly. Any help would be great appreciated. Thanks!

3
In the most straightforward way: var found = strList1.Where(word => strList2.Any(sentence => sentence.Contains(word))).ToList(). Note that this is a quadratic algorithm that tests every combination in the worst case; depending on what list(s) we expect to be big and how long our "words" are more efficient approaches are possible (with things like dedicated full-text indexing at the extreme end). String-searching algorithms are a big topic in computing.Jeroen Mostert

3 Answers

0
votes

I guess this will answer your question

strList1.Where(c => strList2.Any(a => a.Contains(c))).ToList();

0
votes

I can't guarantee performance, but this can be accomplished using Where and Any.

strList1.Where(str => strList2.Any(str2.Contains(str)))

Or for complex objects:

objList1.Where(obj => objList2.Any(obj2.property.Contains(obj.property)))
0
votes

Many ways to do it. Doing linq you could benefit of Intersect, if you first split the "sentences" to "words".

List<string> strList1 = new List<string>() { "oranges", "apples", "grapes" };
List<string> strList2 = new List<string>() {
   "Joe likes peaches",
   "Mack likes apples",
   "Hank likes raisins",
   "Jodi likes grapes",
   "Susan likes apples"  
};

List<string> found = strList1.Intersect(strList2.SelectMany(s => s.Split(" "))).ToList();