开发者

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

This question already has answers here: Closed 11 years ago. 开发者_StackOverflow中文版

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜