简体   繁体   中英

Compare to list<String> using linq?

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

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();

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();

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM