Home > Enterprise >  Compare Arrays in C# using SequenceEqual
Compare Arrays in C# using SequenceEqual

Time:09-17

I am trying to compare two arrays in C# as posted in previous SO post:

Why is the following not working for me:

var first = Value as Array;
var second = other.Value as Array;
bool equal = first.SequenceEqual(second);

I get:

CS1061: 'Array' does not contain a definition for 'SequenceEqual' and no accessible extension method 'Array' accepting a first argument of type 'Array' could be found (are you missing a using directive or an assembly reference?).

I do have the right using at the top:

using System.Linq;

since I can write (no compiler error):

var first = Value as string[];
var second = other.Value as string[];
bool equal = first.SequenceEqual(second);

For reference, I am trying to implement the Equals operator for a generic value type:

public struct MyValue<T> : IEquatable<MyValue<T>> 
{
  public T Value { get; set; }
  public bool Equals(VRValue<T> other) => throw new NotImplementedException();
}

CodePudding user response:

SequenceEqual works with IEnumerable<T>, but Array implements only non-generic IEnumerable, so SequenceEqual does not applicable here.

When casting to the string[], you got different (typed) type of array, which exactly implements IEnumerable<T> (where T is string for this sample)

CodePudding user response:

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);
    }
    [...]
}
  • Related