首页 > 解决方案 > Distinct 上不调用 IEqualityComparer

问题描述

为什么未过滤以下列表中的重复项:

var distinctValues = new[]
{
    new Tuple<int[], int[]>(new[] {1, 2}, new[] {3}),
    new Tuple<int[], int[]>(new[] {2, 3}, new[] {5}),
    new Tuple<int[], int[]>(new[] {1, 2}, new[] {3})
}.Distinct(new TupleEnumerableComparer<int[]>());

我的完整代码如下:

public class TupleEnumerableComparer<T> : IEqualityComparer<Tuple<T, T>> where T : IEnumerable
{
    public bool Equals(Tuple<T, T> left, Tuple<T, T> right)
    {
        if (object.ReferenceEquals(left, right))
        {
            return true;
        }
    
        if (left is null || right is null)
        {
            return false;
        }
        
        return left.Item1.Cast<object>().SequenceEqual(right.Item1.Cast<object>()) &&
           left.Item2.Cast<object>().SequenceEqual(right.Item2.Cast<object>())
    }
    
    public int GetHashCode(Tuple<T, T> obj)
    {
        var valuesInObject = obj.GetType()
            .GetProperties()
            .Select(property => property.GetValue(obj));

        var hash = new HashCode();
        foreach (var value in valuesInObject)
        {
            hash.Add(value);
        }

        return hash.ToHashCode();
    }
}

我已经在上述类的 GetHashCode 和 Equals 中放置了断点,但没有一个被拾取。我做错了什么?谢谢您的帮助。

标签: c#.net.net-corelambda

解决方案


正如@Ralf 在评论中指出的那样,未枚举可枚举:

在结果上调用 ToList 或等效的东西,以便枚举枚举。


推荐阅读