[英]Dictionary custom comparer to get dictinct of custom object
I want to use my comparer MyComparer
to be able to get uniques Vector
s from my dictionary.我想使用我的比较器MyComparer
能够从我的字典中获取唯一的Vector
。 The problem is the result of uniques is wrong.问题是唯一性的结果是错误的。 I tried to put breakpoint inside MyComparer
but somehow when this line is reached var uniques = map.Distinct(new MyComparer());
我试图在MyComparer
中放置断点,但是当到达这条线时不知何故var uniques = map.Distinct(new MyComparer());
it doesn't goes into MyComparer
for unknown reason.由于未知原因,它不会进入MyComparer
。 Why is that?这是为什么? The second point is does the logic inside MyComparer
enough to compare Vector
s in my dictionary and get the uniques?第二点是MyComparer
内部的逻辑是否足以比较我字典中的Vector
并获得唯一性?
Filling up dictionary填写字典
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());
Vector class:矢量 class:
class Vector
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public int D { get; set; }
}
MyComparer我的比较器
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;
}
}
The reason your not seeing it hit the breakpoint is because you're not "resolving" the IEnumerable.您没有看到它到达断点的原因是因为您没有“解析” IEnumerable。
For example when I run this code:例如,当我运行此代码时:
var thing = map.Where(pair => pair.Key == 1);
I get an IEnumerable back, it will only resolve the IEnumerable value (or result) once I use the type.我得到一个 IEnumerable 回来,它只会在我使用该类型时解析 IEnumerable 值(或结果)。 The easiest way to do this is just to add a .ToList();
最简单的方法就是添加一个.ToList();
var uniques = map.Distinct(new MyComparer())
.ToList();
Now your breakpoints should be hit.现在你的断点应该被击中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.