views:

566

answers:

3

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?

+1  A: 

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.

casperOne
+1  A: 

Check out this answer, it provides a method that determines whether two sequences contain the same elements.

Rohan West
+1  A: 

If you want to compare regardless of element order, try the UnorderedEqual<T> method from here:

Otherwise:

var list1 = new List<int> { 1, 2, 3 };
var list2 = new List<int> { 1, 2, 3 };
var areSame = Enumerable.SequenceEqual(list1, list2);
cxfx
cxfx: The poster indicated that they are using C# 3.0 which implies .NET 3.5 which has most of the tools needed to compare IEnumerable<T> implementations as sets, or as ordered sequences, the list equality link doesn't add much to the solution.
casperOne
Thank for your answer, I need to implement IEqualityCompairer interface to do my own comparison actually. The list are:ListA<myObject> , ListB<myObject> ; "myObject" is fairly complex object that I need to compare few property. Thats why I need a custom comparer. In addition those lists are values of two dictionary. So my data model is like this:Dictionary<myObjectA, List<myObjectA>> to be compaired against Dictionary<myObjectB,List<myObjectB>>. Keys are OK but I got problem with Values of those two dictionaryThanks for your replyMorz
Moez
Yes, element order is not a matter
Moez