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
CodePudding user response:
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));
CodePudding user response:
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