Home > Software engineering >  C# Check if list<t> contains any of another list and return the matching item
C# Check if list<t> contains any of another list and return the matching item

Time:05-25

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!

CodePudding user response:

I guess this will answer your question

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

CodePudding user response:

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

CodePudding user response:

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(); 
  • Related