0

I have 3 methods that should return the same data. The data is a list of MyObjectModel and I want to check that the three lists contain the same data. I thought of serializing each of the 3 lists in json and calculating if the length of the strings are all the same.

Is there a better approach?

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • First of all, you need to determine what it means for 2 objects to be equal. All fields the same, same ID, etc. Then you can look at implementing http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx or http://msdn.microsoft.com/en-us/library/ms131187.aspx – Adriaan Stander Oct 23 '12 at 03:48

3 Answers3

6

Use Enumerable.SequenceEqual:

if(list1.SequenceEqual(list2) && list2.SequenceEqual(list3)) {
    ...
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • ok, thanks for the answer, this seems to be what I'm looking for. – frenchie Oct 23 '12 at 03:48
  • Does the order of items in the lists matter here? – Austin Salonen Oct 23 '12 at 03:48
  • @AustinSalonen: no, the order of the elements in each list doesn't matter; as long as they're all there I'm fine. Is there more to it? – frenchie Oct 23 '12 at 04:00
  • In that case you may want to check [this question](http://stackoverflow.com/questions/3669970/compare-two-listt-objects-for-equality-ignoring-order) out. My answer assumed you wanted sequence (order) equality. (Note that the first answer there is very similar; it just sorts the lists first). – nneonneo Oct 23 '12 at 04:02
0

You may want to use a HashSet to do this.

First you add all items from the first list to the HashSet.

Then you iterate the second list, asking to the HashSet if it contains the item or not.

If all are contained there, then they contain the same elements.

Example

var list1 = new string[] { "A", "B", "C" };
var list2 = new string[] { "B", "A", "C" };
var list3 = new string[] { "C", "B", "A" };

var hs = new HashSet<string>(list1);
if (list2.All(x => hs.Contains(x)) && list3.All(x => hs.Contains(x)))
{

}
Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82
0
var isEqual=List<type>.Equals(List1,List2)
var allEqual= isEqual && List<type>.Equals(List1,List3)
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36