Code example:
var positions = new List<Position>();
for (int i = 0; i < 20; i++)
{
positions.Add(new Position { Code = "A", Value = i });
positions.Add(new Position { Code = "A", Value = i });
}
var test = positions.GroupBy(p => p, new PositionComparer());
public class Position
{
public string Code;
public int Value;
}
public class PositionComparer : IEqualityComparer<Position>
{
public bool Equals(Position x, Position y)
{
return x.Code == y.Code && x.Value == y.Value;
}
public int GetHashCode(Position pos)
{
unchecked
{
int hash = 17;
hash = hash * 31 + pos.Code.GetHashCode();
hash = hash * 31 + pos.Value;
return hash;
}
}
}
I have a breakpoint in GetHashCode
(and in Equals
).
The breakpoint is not hit during the GroupBy
, why not?
From the documentation for GroupBy
:
This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.
Unless you actually do something with test
in your code the grouping won't actually be executed and therefore your PositionComparer
won't get executed either.