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
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
try
a.Union(b).Except(a.Intersect(b))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With