38

Possible Duplicate:
LINQ find differences in two lists

I want to find a difference between 2 series. So I am using Except in the LINQ statement. But Except seems to work only when the first collection is longer than the second. For example this will not return any result, even though the 2 collections are different.

double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };

IEnumerable<double> onlyInFirstSet = numbers2.Except(numbers1);

Can anyone confirm if this is the case? If so, do I have to check the collection lengths before I write the query, because I do not know which collection will be bigger at compile time.

Edit

I think I was not clear in my question. I do not care which collection contains what. I just want to find difference between 2 collections. How can I do this?

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
gunnerz
  • 1,898
  • 5
  • 24
  • 39
  • I am not sure whats happening here - but somebody seems to be markinq negative votes to questions/answers. – gunnerz Sep 18 '12 at 15:16
  • Difference how so? `Except` is not symmetric. Are you looking for A.Difference(B) returning everything in A that isn't in B *and* everything in B that isn't in A...or are you looking for something else? – user7116 Sep 18 '12 at 15:19
  • 2
    I found the answer to my question here: http://stackoverflow.com/questions/2404301/linq-find-differences-in-two-lists – gunnerz Sep 18 '12 at 15:22

3 Answers3

62

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

nullify0844
  • 4,641
  • 1
  • 22
  • 16
11

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.

Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • they've misunderstood how it works, they are expecting it to return the items from A and B that aren't equal so if A was {1,2{ and B was {2,3} they are expecting Except to return {1, 3} the wording on the MSDN site is ambiguous – MikeT Nov 11 '15 at 13:59
8

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);
Wasp
  • 3,395
  • 19
  • 37