c# - 未命中 IEqualityComparer + GroupBy 的 GetHashCode 中的断点

标签 c# linq iequalitycomparer

代码示例:

 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 也不会执行。

关于c# - 未命中 IEqualityComparer + GroupBy 的 GetHashCode 中的断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001698/

相关文章:

c# - 连接到远程 MySQL 数据库

c# - 尽管可以访问枚举器,但无法在 CookieCollection 上使用 LINQ

c# - LINQ 在 C# 中使用多个键值选择查询嵌套字典

c# - 如何从重新实现 GetHashCode 的类中获取原始哈希码?

.net - IEqualityComparer<double> 带有容差;如何实现GetHashCode?

c# - 是否可以请求 AWS S3 下载文件?

c# - 下拉菜单 SelctIndexChange 未按预期工作

c# - ICollection<>.Contains 在 EF 中,因为 HashSet 失败

c# - 如何编写没有 Lambda 表达式的函数?

c# - LINQ 方法是扩展方法吗?