简体   繁体   中英

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

10
30

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

10 
30
30

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

Use the Contains method to determine if the element exist in the second list

int[] List1 = { 10, 10029, 30, 30, 10030 };
int[] List2 = { 14,22,23,24,25,26,2728,29,10029,10030 };
var exclusive = List1.Where(x => !List2.Contains(x));
            
foreach (var el in exclusive){
    Console.WriteLine(el);
}

More about Contains - https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=net-6.0

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