Compare to <String> using linq?

I have 3 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 in the main list using linq

+4
source share
3 answers
 var inMaster = List1.Intersect(ListMaster); 

or for both lists:

 var inMaster = List1.Intersect(List2).Intersect(ListMaster); 

check if any item from list1, list2 exists in master

 var existInMaster = inMaster.Any(); 
+5
source

You can use Enumerable.Intersect :

 var inMaster = ListMaster.Intersect(List1.Concat(List2)); 

If you want to know which ones are in List1 that are not in the main list, use Except :

 var newInList1 = List1.Except(ListMaster); 

and for List2 :

 var newInList2 = List2.Except(ListMaster); 

Can I use the .all list to check the entire list item in another list for a list of strings

So you want to know if all the elements of one list are in another list. Then using Except + Any much more efficient (if the lists are large), because Intersect and Except use sets inside, and All - all elements.

So, for example, does the main list contain all the rows List1 and List2 ?

 bool allInMaster = !List1.Concat(List2).Except(ListMaster).Any(); 
+3
source

You can use the Enumerable.Intersect method, for example:

Performs the specified intersection of two sequences, using the default value, compare the values.

 var inMaster1 = List1.Intersect(ListMaster); var inMaster2 = List2.Intersect(ListMaster); 

Here is the DEMO .

+2
source

Source: https://habr.com/ru/post/1483740/


All Articles