[英]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.好的,所以这是一个不好的例子,但基本上,我希望能够创建一个 Linq 调用,以在
strList1
的一个或多个元素中查找strList2
中的任何值并返回找到的值。
So the results would be a list of strList1
items found in ````strList2```.所以结果将是在````strList2```中找到的
strList1
项的列表。 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!
谢谢!
我想这会回答你的问题
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".如果您首先将“句子”拆分为“单词”,那么执行 linq 您可能会受益于
Intersect
。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.