c# - LINQ 按总和分组未按预期工作

标签 c# .net linq .net-4.0

我有这门课:

public class tempClass
{
    public int myKey { get; set; }
    public int total { get; set; }
}

分组和求和的代码:

var list = new List<tempClass>();
list.Add(new tempClass { myKey = 1, total = 1 });
list.Add(new tempClass { myKey = 1, total = 2 });
list.Add(new tempClass { myKey = 2, total = 3 });
list.Add(new tempClass { myKey = 2, total = 4 });
list = list
    .Select(w => new tempClass { myKey = w.myKey, total = w.total })
    .GroupBy(x => new tempClass { myKey = x.myKey })
    .Select(y => new tempClass { myKey = y.Key.myKey, total = y.Sum(z => z.total) })
    .ToList();

list 计数在 GroupBy 之后仍然是 4。

以下代码的结果相同:

list = list
    .GroupBy(x => new tempClass { myKey = x.myKey })
    .Select(y => new tempClass { myKey = y.Key.myKey, total = y.Sum(z => z.total) })
    .ToList();

最佳答案

这样做的原因是您按一个不覆盖 EqualsGetHashCode 的类进行分组。然后使用 System.Object 的实现来比较引用。由于所有都是不同的引用,因此您为每个实例获得一组。

您可以按此属性分组或覆盖 EqualsGetHashCode 来比较此属性:

list = list
    .Select(w => new tempClass { myKey = w.myKey, total = w.total })
    .GroupBy(x => x.myKey)
    .Select(y => new tempClass { myKey = y.Key, total = y.Sum(z => z.total) })
    .ToList();

关于c# - LINQ 按总和分组未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49936488/

相关文章:

c# - 使用 Kinect sdk for windows v 2.0 调整 kinect 相机角度

c# - 类 Base64 字符串转换,到更小的字符集

c# - 如何在 C# 中将 DataTable 转换为 XML 文件?

c# - 我可以在同一参数中同时接受委托(delegate)类型 T 和 Expression<T> 吗?

c# - 如何添加对由 C# 项目调用的非托管 C++ 项目的引用?

c# - 拦截鼠标/键盘事件

.net - 在 Dev Machine 上备份 Visual Studio 解决方案的最佳实践

c# - Telegram C# 示例发送消息

c# - 如何向 ThenInclude 添加 where 子句

C# 使用 LINQ 对通用列表<>进行分组/排序