C# 使用Linq比较或匹配两个通用列表集

C# 使用Linq比较或匹配两个通用列表集,c#,linq,.net-4.5,C#,Linq,.net 4.5,参考许多链接进行列表比较,但我还没有弄清楚列表之间的匹配 Let's say I have two lists of strings: List1: "apple, orange, mango, bananna, butter fruit" List2: "butter fruit, grapes, apple, bananna, orange, mango, jack fruit, pineapple" 这里我需要检查List1项是否在List2集中。如果存在,则返回true,否则返

参考许多链接进行列表比较,但我还没有弄清楚列表之间的匹配

Let's say I have two lists of strings:

 List1: "apple, orange, mango, bananna, butter fruit"

 List2: "butter fruit, grapes, apple, bananna, orange, mango, jack fruit, pineapple"
这里我需要检查List1项是否在List2集中。如果存在,则返回true,否则返回false

我尝试了使用Except,但在两组之间没有得到预期的结果true或false

if(List1.Except(List2).Count == 0)
{
  ....
}
除了

if(list1.Except(list2).Any())
{
   //....
}
With All(Bobson的注释:注意,如果list1为空,则.All()将成功,但其他两个不会成功):

任何:

list1.Any(str => !list2.Contains(str));

您可以使用
All
方法:

return list1.All(list2.Contains);

如果list1中的所有元素都在list2中,是否要得到True,或者列表1中每个元素的true/false列表?如果列表1中的项目在列表2中出现,我只需要true。您要求我们诊断代码的问题,而您甚至没有提供不起作用的代码。@sukumar您在
Count
中缺少括号,应该是
Count()
,除此之外,你的方法没有任何问题。我展示了我的努力,但仍然投了反对票。为什么?请注意,如果
列表1
为空,则
.All()
将成功,但其他两个不会成功。+1如果列表很长,您可以考虑将list2推到一个HashSet中,然后调用其中包含的…@digEmAll,这正是
要为您做的事情,除了
return list1.All(list2.Contains);