簡體   English   中英

字典自定義比較器以獲取自定義 object 的字典

[英]Dictionary custom comparer to get dictinct of custom object

我想使用我的比較器MyComparer能夠從我的字典中獲取唯一的Vector 問題是唯一性的結果是錯誤的。 我試圖在MyComparer中放置斷點,但是當到達這條線時不知何故var uniques = map.Distinct(new MyComparer()); 由於未知原因,它不會進入MyComparer 這是為什么? 第二點是MyComparer內部的邏輯是否足以比較我字典中的Vector並獲得唯一性?

填寫字典

var map = new Dictionary<Vector, int>();
for (int i = 0; i < N; i++)
                map.Add(new Vector { A = s[0, i], B = s[0, i + 1], C = s[1, i], D = s[1, i + 1] }, i);

            var uniques = map.Distinct(new MyComparer());

矢量 class:

class Vector
{
            public int A { get; set; }
            public int B { get; set; }
            public int C { get; set; }
            public int D { get; set; }
}

我的比較器

class MyComparer : IEqualityComparer<KeyValuePair<Vector, int>>
{
       public bool Equals(KeyValuePair<Vector, int> x, KeyValuePair<Vector, int> y)
       {
             return x.Key == y.Key;
       }

       public int GetHashCode(KeyValuePair<Vector, int> obj)
       {
           return 1;
       }
}

您沒有看到它到達斷點的原因是因為您沒有“解析” IEnumerable。

例如,當我運行此代碼時:

var thing = map.Where(pair => pair.Key == 1);

我得到一個 IEnumerable 回來,它只會在我使用該類型時解析 IEnumerable 值(或結果)。 最簡單的方法就是添加一個.ToList();

var uniques = map.Distinct(new MyComparer())
                .ToList();

現在你的斷點應該被擊中。

暫無
暫無

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

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