.net - recursive assert on collection -
i test one:
[test] public void testcollectionassert () { var a1 = new [] { new [] { "a" } }; var a2 = new [] { new [] { "a" } }; assert.arenotequal (a1, a2); //collectionassert.areequal (a1, a2); collectionassert.areequivalent (a1, a2); }
to pass. real case more complicated, solving 1 in generic way do. ideas?
there's useful linq operator called sequenceequal()
compares 2 sequences equality. sequenceequal()
walks through 2 ienumerable<>
sequences , verifies have same number of elements , elements @ same index equal (using default equality comparer). however, since have nested collections, need extend concept of equality apply them well. fortunately, there's overload allows supply own iequalitycomparer<>
object.
since it's awkward have define class provide equality semantics, i've written generic extension allows use delegate instead. let's @ code:
public static class comparerext { private class genericcomparer<t> : iequalitycomparer<t> { private readonly func<t, t, bool> m_equalityfunc; public genericcomparer( func<t,t,bool> comparefunc ) { m_equalityfunc = comparefunc; } public bool equals(t x, t y) { return m_equalityfunc(x, y); } } // converts delegate icomparer public static iequalitycomparer<t> areequal<t>( func<t,t,bool> comparefunc ) { comparefunc.throwifnull("comparefunc"); return new genericcomparer<t>(comparefunc); } }
now, can compare 2 sequences enough:
assert.istrue( // check outer sequences equivalent... a1.sequenceequal( a2, // define equality inner sequences being equal... comparerext.areequal( (a,b) => a.sequenceequal(b) ) );
Comments
Post a Comment