简体   繁体   English

如何获取 Entity Framework Core 中的字段总和?

[英]How to get sum of fields in Entity Framework Core?

I have a table like this in SQL Server and a model class in C# with Entity Framework Core:我在 SQL 服务器和 model class 中有一个这样的表在 ZD7EFA19FBE7D3972FD5ADB6024

id ID relatedId相关标识 dec1十二月1 dec2十二月2
1 1 1 1 540000 540000 250000 250000
2 2 1 1 255000 255000 200000 200000
3 3 2 2 100 100 200 200
4 4 2 2 500 500 400 400

Now I want get sum of dec1 and dec2 for relatedId 1 and 2 seperatly.现在我想分别获取relatedId 1 和 2 的 dec1 和 dec2 的总和。 like this:像这样:

relatedId1 sum dec1 = 7950000 and sum dec2 = 450000
relatedId2 sum dec1 - 600 and dec2 = 600

in my C# code.在我的 C# 代码中。

Thanks谢谢

Try using the GroupBy , and Sum , like so,尝试使用GroupBySum ,就像这样,

var summ = entName.GroupBy(t => t.relatedId)
                           .Select(t => new
                           {
                               relatedId = t.Key,
                               dec1Sum = t.Sum(d => d.dec1),
                               dec2Sum = t.Sum(d => d.dec2),
                           }).ToList();

//print the results
summ.ForEach(t => Console.WriteLine($"relatedId {t.relatedId}, sum for dec1 : {t.dec1Sum}, sum for dec2 : {t.dec2Sum}"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM