Comparing Structure of Nested Collections

262 views Asked by At

When using Microsoft Visual Studio's built-in unit testing framework, how do I compare two collections that contain nested collections for equality when child collections are considered equal if their contents are equal?

In the below example, AreEquals fails because each list contains a different nested list instance.

var a = new List<List<string>> { new List<string> { "a" } };
var b = new List<List<string>> { new List<string> { "a" } };

CollectionAssert.AreEqual(a, b);

I'm looking for an assertion that returns true when comparing a and b because the nested collections match in structure/contents even though they are not the same list instance.

Am I missing an easy way to do this? Writing an IEqualityComparer<T> is an option but I'm hoping there's a simple route.... :-)

1

There are 1 answers

2
paparazzo On
public bool AreEqual(List<List<string>> la, List<List<string>> lb)
{   
    if(la == null || lb == null) return false;
    if(la.Count() != lb.Count()) return false;
    for(int i; i ++; i < la.Count()) 
    {
       if(la[i].Count() != lb[i].Count()) return false;
       for(int j; j ++; j < la[i].Count()) 
       {
           if(la[i][j] != lb[i][j]) return false;
       }
    }
    return true;
}