为什么Distinct(Linq)在int []列表中不起作用?

时间:2020-06-30 10:09:38

标签: c# linq distinct

我写了这个方法。应该从a ^ 2 + b ^ 2 = c ^ 2的整数数组中返回所有三元组[a,b,c]。

public static List<int[]> AllTripletsThatFulfilla2b2c2Equality(int[] n)
    {
        var combinations = from i in n
                           from j in n
                           from p in n
                           select new int[][] {new int[]{ i, j, p }, new int[] {p, j, i}, new int[] {i, p, j}};
        
        return combinations.Where(x => x.Length == x.Distinct().Count() && Math.Pow(x[0], 2) + Math.Pow(x[1], 2) == Math.Pow(x[2], 2)).Distinct().ToList();
    }

区别不起作用。

我尝试了其他几种编写方式,包括

public static List<int[]> AllTripletsThatFulfilla2b2c2Equality(int[] n)
    {
        var combinations = from i in n
                           from j in n
                           from p in n
                           select new[] { i, j, p };
        combinations = combinations.ToList();
        Func<int[], List<int[]>> combo = x =>
        {
            List<int[]> list = new List<int[]>();
            list.Add(x);
            if (!combinations.Contains(new [] { x[0], x[2], x[1] }))
            {
                list.Add(new[] { x[0], x[2], x[1] });
            }


            if (!combinations.Contains(new[] { x[2], x[1], x[0] }))
            {
                list.Add(new[] { x[2], x[1], x[0] });
            }
            list.Add(new [] { x[0], x[2], x[1] });
            list.Add(new [] { x[2], x[1], x[0] });
            return list;
        };

        return combinations.SelectMany(combo).Distinct().Where(x => x.Length == x.Distinct().Count() && Math.Pow(x[0], 2) + Math.Pow(x[1], 2) == Math.Pow(x[2], 2)).ToList();
    }

甚至为Distinct添加了比较器:

        public class TripletComparer : IEqualityComparer<int[]>
    {
        public bool Equals(int[] x, int[] y)
        {
            return x[0] == y[0] && x[1] == y[1] && x[2] == y[2];
        }

        public int GetHashCode(int[] obj)
        {
            return obj.GetHashCode();
        }
    }

相同的测试结果,

Assert.Equal() Failure
Expected: List<Int32[]> [[3, 4, 5], [4, 3, 5]]
Actual:   List<Int32[]> [[3, 4, 5], [3, 4, 5], [4, 3, 5], [4, 3, 5], [4, 3, 5], ...]

以某种方式,它看不到有重复的项目。有谁知道为什么,以及如何解决?

1 个答案:

答案 0 :(得分:0)

您的GetHashCode实现似乎很奇怪。通常,您会根据实际Equals检查中使用的完全相同的成员来计算哈希码。否则,Distinct可能甚至不会调用您的Equals方法。

public bool Equals(int[] x, int[] y)
{
    return x[0] == y[0] && x[1] == y[1] && x[2] == y[2];
}

public int GetHashCode(int[] obj)
{
    int hash = 17;
    // Suitable nullity checks etc, of course :)
    hash = hash * 23 + obj[0].GetHashCode();
    hash = hash * 23 + obj[1].GetHashCode();
    hash = hash * 23 + obj[2].GetHashCode();
    return hash;
}

免责声明:哈希码改编自https://stackoverflow.com/a/263416/2528063