Reputation: 310
How to create the exactly following two for's in lambda expression?
foreach (var item in list1)
{
foreach (var item2 in list2)
{
if (item.number == item2.number)
{
return false;
}
}
}
Upvotes: 1
Views: 383
Reputation: 391
Here you go !!
Using Linq Method Syntax :
!list1.Any(item => list2.Any(item2 => item.number == item2.number))
Using Linq Query syntax:
!(from item in list1
from item2 in list2
where item.number==item2.number select item).Any()
Upvotes: 0
Reputation: 943
I would just use the Intersect
function available for lists and this will return you all the elements that are common in 2 lists. If you just want to see if one exists then you can do it very easily by checking the count.
int count = List1.Select(s => s.number).Intersect(List2.Select(s => s.number)).Count;
If you want to know which elements are unique in both lists then use the Exclude method.
var uniqueItems = List1.Select(s => s.number).Except(List2.Select(s => s.number));
Upvotes: 2
Reputation: 52280
Since you're just checking to see if any one item matches, you can use Any()
.
return !list1.Any( item1 => list2.Any(item2 => item2 == item1 ));
Upvotes: 3