.NET/C#: what is the meaning of “Comparing two IEnumerables for equality”?
Posted by jpluimers on 2013/01/09
Until I realized that comparing two IEnumerables needed some extra thought, I wondered why Assert.AreEqual would not support them.
jrista pointed me in the right direction answering a question about c# – How does Assert.AreEqual determine equality between two generic IEnumerables?
The correct answer is “it doesn’t”, but that is really dense.
IEnumerables are just that: being generic or normal, they allow you to enumerate things. They can get you an enumerator (generic or not) that has a notion of Current (generic or normal) and such, but no knowledge of the underlying data.
Comparing them needs you to think about the enumeration and the underlying data at the same time. You can get two kinds of comparisons:
Often: exact equality
What you usually want with an AreEqual on two IEnumerable references is to return true the values in the order of the returned IEnumerator references are satisfy AreEqual too.
jrista didn’t get that completely right, because he expects IEnumerable to have a Count (so you can short circuit when the Counts values mismatch), however only ICollection (both generic and normal) each have their (generic and normal) Count.
The code can be easier when using the Enumerable.SequenceEqual(TSource) Method that got introduced with LINQ as pointed out by Jason Baker.
But also: equivalence
Sometimes though, you want to test the IEnumerables for equivalence. That is: match their contents regardless of their order.
That is where the CollectionAssert class is very convenient. Though only based on normal ICollection they have a bunch of handy methods, including AreEquivalent as bacar has pointed out and Mark Seeman has pointed out as well.
You can use generic ICollection references with CollectionAssert, you just have to perform either of these two first as Lee has pointed out:
- perform a ToList on the ICollection<T>, as List<T> implements the normal IList which implements the normal ICollection
- perform a ToArray on the ICollection<T>, as the single dimensional typed array implements the normal ICollection too
–jeroen
via: c# – How does Assert.AreEqual determine equality between two generic IEnumerables? – Stack Overflow.






Leave a comment