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
How to Clear Browser Cache on Browser Back Button Click in MVC4
Interaction Between Webbrowser Control and Windows Forms
Does Dispose Still Get Called When Exception Is Thrown Inside of a Using Statement
How to Create Trial Version of .Net Software
Monitor a Process's Network Usage
Generating a Random Decimal in C#
Differencebetween .Equals and ==
How to Add Moving Effects to My Controls in C#
Get Instance of Excel Application with C# by Handle
Outofmemoryexception When I Read 500Mb Filestream
How to Create a Sequence of Integers in C#
Writing to Then Reading from a Memorystream
Get Ipv4 Addresses from Dns.Gethostentry()
How to Run External Program via a C# Program
How to Add Http Header to Soap Client
C# 4.0: How to Use a Timespan as an Optional Parameter with a Default Value