Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return exclusive elements from two lists that comes more than twice using linq

I have two lists:

    int[] List1 = { 10, 10029, 30, 30, 10030 };
    int[] List2 = { 14,22,23,24,25,26,2728,29,10029,10030 };

and the following statement,

var NewList = List1.Except(List2);

returns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

10
30

but I want the output to include the exclusive elements that have been duplicated. So,

10 
30
30

>Solution :

LINQ with the semantics you’re looking for:

var newList = List1.Where(x => !List2.Contains(x));

Note that this is quadratic in the size of the lists. If the lists are large then this might take a long time. To alleviate that, you can turn the other list to a set first, for fast lookup:

var list2AsSet = List2.ToHashSet();
var newList = List1.Where(x => !list2AsSet.Contains(x));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading