The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,909 other followers

.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:


via: c# – How does Assert.AreEqual determine equality between two generic IEnumerables? – Stack Overflow.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: