Home > Back-end >  Dictionary custom comparer to get dictinct of custom object
Dictionary custom comparer to get dictinct of custom object

Time:11-24

I want to use my comparer MyComparer to be able to get uniques Vectors from my dictionary. 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()); it doesn't goes into MyComparer for unknown reason. Why is that? The second point is does the logic inside MyComparer enough to compare Vectors in my dictionary and get the uniques?

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

CodePudding user response:

The reason your not seeing it hit the breakpoint is because you're not "resolving" the 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. The easiest way to do this is just to add a .ToList();

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

Now your breakpoints should be hit.

  •  Tags:  
  • c#
  • Related