简体   繁体   中英

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

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!

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

我想这会回答你的问题

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM