使用 SequenceEqual 在 C# 中比较数组
Compare Arrays in C# using SequenceEqual
我正在尝试比较 C# 中的两个数组,如 posted 在之前的 SO post:
- Easiest way to compare arrays in C#
为什么以下内容对我不起作用:
var first = Value as Array;
var second = other.Value as Array;
bool equal = first.SequenceEqual(second);
我得到:
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?).
我确实有在顶部使用的权利:
using System.Linq;
因为我会写(没有编译错误):
var first = Value as string[];
var second = other.Value as string[];
bool equal = first.SequenceEqual(second);
作为参考,我正在尝试为通用值类型实现 Equals
运算符:
public struct MyValue<T> : IEquatable<MyValue<T>>
{
public T Value { get; set; }
public bool Equals(VRValue<T> other) => throw new NotImplementedException();
}
SequenceEqual
与 IEnumerable<T>
一起使用,但 Array
仅实现非泛型 IEnumerable
,因此 SequenceEqual
不适用于此处。
转换为 string[]
时,您得到了不同的(类型化的)数组类型,它完全实现了 IEnumerable<T>
(其中 T 是该示例的字符串)
根据@Sweeper/@Jeppe Stig Nielsen 的建议,我将函数重写为:
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);
}
[...]
}
使用HashSet时,还要注意GetHashCode:
public override int GetHashCode()
{
if (typeof(T).IsArray)
{
var first = Value as IStructuralEquatable;
return StructuralComparisons.StructuralEqualityComparer.GetHashCode(first);
}
[...]
}
我正在尝试比较 C# 中的两个数组,如 posted 在之前的 SO post:
- Easiest way to compare arrays in C#
为什么以下内容对我不起作用:
var first = Value as Array;
var second = other.Value as Array;
bool equal = first.SequenceEqual(second);
我得到:
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?).
我确实有在顶部使用的权利:
using System.Linq;
因为我会写(没有编译错误):
var first = Value as string[];
var second = other.Value as string[];
bool equal = first.SequenceEqual(second);
作为参考,我正在尝试为通用值类型实现 Equals
运算符:
public struct MyValue<T> : IEquatable<MyValue<T>>
{
public T Value { get; set; }
public bool Equals(VRValue<T> other) => throw new NotImplementedException();
}
SequenceEqual
与 IEnumerable<T>
一起使用,但 Array
仅实现非泛型 IEnumerable
,因此 SequenceEqual
不适用于此处。
转换为 string[]
时,您得到了不同的(类型化的)数组类型,它完全实现了 IEnumerable<T>
(其中 T 是该示例的字符串)
根据@Sweeper/@Jeppe Stig Nielsen 的建议,我将函数重写为:
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);
}
[...]
}
使用HashSet时,还要注意GetHashCode:
public override int GetHashCode()
{
if (typeof(T).IsArray)
{
var first = Value as IStructuralEquatable;
return StructuralComparisons.StructuralEqualityComparer.GetHashCode(first);
}
[...]
}