簡體   English   中英

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

[英]Why doesn't Distinct (Linq) work in a List of int[]?

我寫了這個方法。 它應該從整數數組中返回所有三元組 [a, b, c],其中 a ^ 2 + b ^ 2 = c ^ 2。

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], ...]

不知何故,它沒有看到有重復的項目。 有誰知道為什么,以及如何解決它?

您的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;
}

免責聲明:hashcode-code 改編自https://stackoverflow.com/a/263416/2528063

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM