找到LINQ查询是否在列表中的项目都包含在另一个列表 [英] LINQ query to find if items in a list are contained in another list
问题描述
我有以下的code:
列表<串GT;测试1 =新的List<串GT; {@ bob.com,@ tom.com};
清单<串GT;测试2 =新的List<串GT; {joe@bob.com,test@sam.com};
我需要在TEST2删除任何人有@ bob.com或@ tom.com。
我曾尝试是这样的:
布尔bContained1 = test1.Contains(测试2);
布尔bContained2 = test2.Contains(TEST1);
bContained1 = FALSE
,但 bContained2 = TRUE
。我想preFER不遍历每个列表,而是使用LINQ查询检索数据。 bContained1是,我下面创建LINQ查询在相同的条件:
列表<串GT; TEST3 = test1.Where(W =>!test2.Contains(重量))了ToList();
查询上述工程上的完全一致,但没有部分匹配。
我已经看过其他的查询,但我能找到的LINQ密切与此相比。任何意见或任何地方,你可以点我将是一个很大的帮助。
VAR test2NotInTest1 = test2.Where(T2 => test1.Count(T1 => t2.Contains(T1 ))== 0);
更快的版本根据Tim的建议:
VAR test2NotInTest1 = test2.Where(T2 =>!test1.Any(T1 => t2.Contains(T1)));
I have the following code:
List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "joe@bob.com", "test@sam.com" };
I need to remove anyone in test2 that has @bob.com or @tom.com.
What I have tried is this:
bool bContained1 = test1.Contains(test2);
bool bContained2 = test2.Contains(test1);
bContained1 = false
but bContained2 = true
. I would prefer not to loop through each list but instead use a Linq query to retrieve the data. bContained1 is the same condition for the Linq query that I have created below:
List<string> test3 = test1.Where(w => !test2.Contains(w)).ToList();
The query above works on an exact match but not partial matches.
I have looked at other queries but I can find a close comparison to this with Linq. Any ideas or anywhere you can point me to would be a great help.
var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);
Faster version as per Tim's suggestion:
var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));
这篇关于找到LINQ查询是否在列表中的项目都包含在另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!