繁体   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