我有这门课:
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();
最佳答案
这样做的原因是您按一个不覆盖 Equals
和 GetHashCode
的类进行分组。然后使用 System.Object
的实现来比较引用。由于所有都是不同的引用,因此您为每个实例获得一组。
您可以按此属性分组或覆盖 Equals
和 GetHashCode
来比较此属性:
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/