Reputation: 1158
I have 3 list List
ListMaster contains {1,2,3,4,....} ..getting populated from DB
List1 contains {1,3,4}
List2 contains {1,3,95}
how to check Which list items are present in master list using linq
Upvotes: 4
Views: 251
Reputation: 60493
var inMaster = List1.Intersect(ListMaster);
or for both list :
var inMaster = List1.Intersect(List2).Intersect(ListMaster);
check if any item from list1, list2 exist in master
var existInMaster = inMaster.Any();
Upvotes: 5
Reputation: 98750
You can use Enumerable.Intersect
method like;
Produces the set intersection of two sequences by using the default equality comparer to compare values.
var inMaster1 = List1.Intersect(ListMaster);
var inMaster2 = List2.Intersect(ListMaster);
Here is a DEMO
.
Upvotes: 2
Reputation: 460158
You can use Enumerable.Intersect
:
var inMaster = ListMaster.Intersect(List1.Concat(List2));
If you want to know which are in List1
which are not in the master-list, use Except
:
var newInList1 = List1.Except(ListMaster);
and for List2
:
var newInList2 = List2.Except(ListMaster);
Can i use a list .all to check all item of a list in another list for list of string
So you want to know if all items of one list are in another list. Then using Except
+ Any
is much more efficient(if the lists are large) because Intersect
and Except
are using sets internally whereas All
loops all elements.
So for example, does the master-list contain all strings of List1
and List2
?
bool allInMaster = !List1.Concat(List2).Except(ListMaster).Any();
Upvotes: 3