未命中 IEqualityComparer + GroupBy 的 GetHashCode 中的断点

Breakpoint in GetHashCode of IEqualityComparer + GroupBy not hit

代码示例:

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

我在 GetHashCode(和 Equals)中有一个断点。
GroupBy 期间没有命中断点,为什么?

来自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.

除非您在代码中实际使用 test 执行某些操作,否则实际上不会执行分组,因此您的 PositionComparer 也不会执行。