Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

easiest way to compare not trivial enumerable

What’s the easiest way to compare non trivial sequences without writing loads of custom code with boilerplate?

This example obviously doesn’t work, but short of writing a completely custom routine, is there some sort of shortcut?

[TestMethod]
public void FooTest()
{
    var x = new[]
    {
        ("0", new[] { 0, 105}),
        ("1", new[] { 1 }),
        ("2", new[] { 2 })
    };
    var y = new[]
    {
        ("0", new[] { 0, 105}),
        ("1", new[] { 1 }),
        ("2", new[] { 2 })
    };

    Assert.AreEqual(x,y);
}

There is Enumerable.SequenceEqual, I assume I need a custom EqualityComparer<>? Which feels like a massive overkill when all I want to do is pass something to say whether a non null element a, doesn’t equal a non null element b.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is using MSUnit, but to be fair the question is general and ideally I shouldnt be assuming I’m using some testing framework, this is my best solution so far.

[TestMethod]
public void FooTest()
{
    var xs = new[]
    {
        ("0", new[] { 0,105}),
        ("1", new[] { 1 }),
        ("2", new[] { 2 })
    };
    var ys = new[]
    {
        ("0", new[] { 0,105}),
        ("1", new[] { 1 }),
        ("2", new[] { 2 })
    };

    static bool CompareEnumerable<T>(IEnumerable<T> xs, IEnumerable<T> ys, Func<(T, T), bool> isEqual)
    {
        if (xs == ys)
            return true;
        if (xs.LongCount() != ys.LongCount())
            return false;
        return xs.Zip(ys).All(isEqual); 
    }

    var areEqual = CompareEnumerable(xs, ys, xy =>
    {
        if (xy.Item1.Item1 != xy.Item2.Item1)
            return false;

        return CompareEnumerable(xy.Item1.Item2, xy.Item2.Item2,xy => xy.Item1 == xy.Item2);
    });

    Assert.IsTrue(areEqual);
}

but its quite inefficient (I’m checking lengths), and surely its a lot of code!

>Solution :

Which testing tool are you using? With Xunit, Assert.Equal method returns the expected result.

var x = new[]
{
    ("0", new[] { 0,105 }),
    ("1", new[] { 1 }),
    ("2", new[] { 2 })
};

var y = new[]
{
    ("0", new[] { 0,105 }),
    ("1", new[] { 1 }),
    ("2", new[] { 2 })
};

Assert.Equal(x, y); // true
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading