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))
I think that what you have is probably the best way to do this from the standpoint of simple code.
Depending on what your end goal is, there may be ways to make it more readable, though.
精彩评论