Possible Duplicate:
Is there a built-in method to compare collections in C#?
What is the best way to compare to generic two generic lists in C# 3.0?
If you want to compare regardless of element order, try the UnorderedEqual<T> method from here:
- C# List Element Equality
Otherwise:
var list1 = new List<int> { 1, 2, 3 };
var list2 = new List<int> { 1, 2, 3 };
var areSame = Enumerable.SequenceEqual(list1, list2);
Check out this answer, it provides a method that determines whether two sequences contain the same elements.
If you want to compare two sequences in .NET 3.5 and beyond (that's the version of the framework which C# 3.0 ships with), then you should use the SeqenceEqual extension method on the Enumerable class in the System.Linq namespace.
However, for this, it will use the default equality comparer for the type parameter T in the IEnumerable<T>
implementations it is comparing.
If you want to change the way that equality is checked for, then you should pass an implementation of IEqualityComparer<T>
to the SequenceEqual method to use when comparing the items from each sequence.
Also, if you are trying to see if two sets are equal (as represented by IEnumerable<T>
) then your best bet is to check use the Except extension method on the Enumerable class and make sure that the result set doesn't have any entries, and that both IEnumerable<T>
implementations have the same number of entries (since Except can return an empty sequence even with different length sequences passed to it) which you can do with the Count extension method.
精彩评论