[英]How to get SUM of column using Entity Framework LINQ
I want to get SUM of column "Weight" using LINQ and store in list. 我想使用LINQ获取“重量”列的SUM并存储在列表中。 Following is code of join operation of two columns. 以下是两列的联接操作代码。
var que = (from o in db.OrderPlans.Where(i => i.DemandId == _demandId)
join f in db.Fabrics
on o.FabricId equals f.Id
select new
{
f.Id,
f.Name,
o.Width,
f.Type,
o.GSM,
o.Weight
}).ToList();
assuming the code you posted above works and let's pretend you stored that in a variable called joinedList (and that you want the sum of Weight across groups formed by the distinct combinations of all the other fields): 假设您上面发布的代码有效,并且假设您将其存储在一个名为joinedList的变量中(并且您希望将由所有其他字段的不同组合形成的组的权重之和):
var groupedList = joinedList.GroupBy(grp => new {
grp.Id,
grp.Name,
grp.Width,
grp.Type,
grp.GSM
}).Select(grp => new {
grp.Key.Id,
grp.Key.Name,
grp.Key.Width,
grp.Key.Type,
grp.Key.GSM,
SumOfWeight = grp.Sum(w => w.Weight)
}).ToList();
在您的代码末尾附加此.Groupby(w => w.Weight).Convert< int >(g=> g.Sum());
It seems to me that you have a one-to-many relation between Fabric
and OrderPlan
: every Fabric
has zero or more OrderPlans
, every OrderPlan
belongs to exactly one Fabric
, namely the Fabric
that the foreign key refers to. 在我看来, Fabric
和OrderPlan
之间存在一对多的关系:每个Fabric
具有零个或多个OrderPlans
,每个OrderPlan
完全属于一个Fabric
,即外键引用的Fabric
。
It seems to me that you want several Fabric
properties with (several properties of) their OrderPlans
and the total Weight of these OrderPlans
. 在我看来,您想要具有其OrderPlans
(的几个属性)和这些OrderPlans
的总权重的几个Fabric
属性。
Whenever you have a one-to-many relation or many-to-many relation and you want to fetch "items with their sub-items", like Schools with their Students, or Customers with their Orders, or Orders with their OrderLines, you use Queryable.GroupJoin instead of a standard join. 每当您具有一对多关系或多对多关系并且想要获取“带有子项的项目”时,例如学校与学生,客户与订单或订单与订单行,例如使用Queryable.GroupJoin而不是标准联接 。
// GroupJoin Fabrics with some of their OrderPlans:
var result = dbContext.Fabrics
.GroupJoin(dbContext.OrderPlans.Where(orderPlan => ...)
fabric => fabric.Id, // from each Fabric take the primary key
orderPlan => orderPlan.FabricId, // from each OrderPlan take the foreign key
// ResultSelector: take every Fabric with all his matching OrderPlans to make one new object:
(fabric, orderPlansOfthisFabric) => new
{
// Select the Fabric properties you want
Id = fabric.Id,
Name = fabric.Name,
Type = fabric.Type,
OrderPlans = orderPlansOfThisFabric.Select(orderPlan => new
{
// Select the OrderPlan properties you want:
Width = orderPlan.Width,
Gsm = orderPlan.Gsm,
}
// Weight: calculate the sum of all OrderPlans of this Fabric:
Weight = orderPlansOfThisFabric
.Select(orderPlan => orderPlan.Weight)
.Sum(),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.