Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does LINQ Except work? [duplicate]

Tags:

linq

except

People also ask

How does LINQ except work?

LINQ: Except The Except() method requires two collections. It returns a new collection with elements from the first collection which do not exist in the second collection (parameter collection). Except extension method doesn't return the correct result for the collection of complex types.

Does LINQ Union remove duplicates?

Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.

Is LINQ inefficient?

Conclusion. It would seem the performance of LINQ is similar to more basic constructs in C#, except for that notable case where Count was significantly slower. If performance is important it's crucial to do benchmarks on your application rather than relying on anecdotes (including this one).


Taken from 101 LINQ Samples:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 

IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); 

Console.WriteLine("Numbers in first array but not second array:"); 
foreach (var n in aOnlyNumbers) 
{ 
    Console.WriteLine(n); 
}

Result

Numbers in first array but not second array: 0 2 4 6 9


For example this will not return any result...

That's correct.

2.2 exists in the first collection, so there is nothing to return.

It has nothing to do with the lengths of the arrays.


The other answers are telling you how you can remove a set of numbers from another set. Reading your question I think you want what's in the first but not in the second, and viceversa:

var numbers1 = new [] { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
var numbers2 = new [] { 2.2, 2.8 };

var intersect = numbers1.Intersect(numbers2);
var diff = numbers1.Concat(numbers2).Except(intersect);