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