Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to find a difference between two arrays [duplicate]

Tags:

arrays

c#

linq

Possible Duplicate:
Getting the “diff” between two arrays in C#?

Is there a better way to get the difference of two arrays?

var a = new int[] { 1, 2, 3 };
var b = new int[] { 2, 3, 4 };

foreach (var d in a.Except(b).Union(b.Except(a)))
    Console.WriteLine(d); // 1 4
like image 613
MrCoocoo Avatar asked Aug 03 '11 14:08

MrCoocoo


2 Answers

You're looking for the symmetric-difference, an operator that LINQ to Objects doesn't have yet (as of .NET 4.0). The way you've done it is perfectly fine - although you might want to consider extracting that bit out into a method of its own.

However, a more efficient way of accomplishing this would be with the HashSet<T>.SymmetricExceptWith method.

var result = new HashSet<int>(a);
result.SymmetricExceptWith(b);

foreach (var d in result)
   Console.WriteLine(d); // 1 4
like image 103
Ani Avatar answered Sep 25 '22 02:09

Ani


try

a.Union(b).Except(a.Intersect(b))
like image 44
Yahia Avatar answered Sep 24 '22 02:09

Yahia