Testing Equality of Arrays in C#

Testing equality of arrays in C#

By using LINQ you can implement it expressively and performant:

var q = from a in ar1
join b in ar2 on a equals b
select a;

bool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length;

Easiest way to compare arrays in C#

You could use Enumerable.SequenceEqual. This works for any IEnumerable<T>, not just arrays.

check if a list of array contains an array in c#

Use SequenceEqual method from System.Linq

static bool CheckContains(List<int[]> forbiddenChoice, int[] finalChoice)
{
for (int i = 0; i < forbiddenChoice.Count; i++)
{
if (forbiddenChoice[i].SequenceEqual(finalChoice))
{
return true;
}
}
return false;
}

Compare Arrays in C# using SequenceEqual

Using @Sweeper/@Jeppe Stig Nielsen suggestions, I rewrote my function as:

public bool Equals(VRValue<T> other)
{
if (typeof(T).IsArray)
{
var first = Value as IStructuralEquatable;
var second = other.Value as IStructuralEquatable;
return StructuralComparisons.StructuralEqualityComparer.Equals(first, second);
}
[...]
}

When using a HashSet, one should also pay attention to GetHashCode:

public override int GetHashCode()
{
if (typeof(T).IsArray)
{
var first = Value as IStructuralEquatable;
return StructuralComparisons.StructuralEqualityComparer.GetHashCode(first);
}
[...]
}

How do you unit test if two jagged arrays are equal?

Since you cannot use the Hashcode which uses the reference rather than the content of an array, the way to go would be to iterate all values in a nested loop, compare value by value (as in stackoverflow.com/questions/2893297/iterate-multi-dimensional-array-with-nested-foreach-statement), use a boolean which you set to false at the first mismatch, and assert that this boolean is true in your unit test.

A better way to compare the equality of two arrays?

If you need the sequence to be equal as well then:

You can use Enumerable.SequenceEqual

var IsEqual = sut.DataFields.SequenceEqual(expected);


Related Topics



Leave a reply



Submit