简体   繁体   English

通过父代对子记录进行分组,并对linq C#求和

[英]group child records by parentid and sum the amount linq C#

I have a model with three properties 我有一个具有三个属性的模型

id int {get; set:}
name varchar {get; set:}
int fundedamount {get;set;}
list<child> childlist {get; set:}

and child like this 和这个孩子

int id{get;set;}
int parentid{get;set;}
int amount{get;set;}

I want to group child records by parentid and sum the amount and assign it to parent.fundedamount using linq. 我想通过父代对子记录进行分组并求和,然后使用linq将其分配给parent.fundedamount。

i am trying it like this: 我正在这样尝试:

 model.ForEach(f => f.childlist.Where(f1 => f1.parentid== f.Id).Sum(f2 => f2.Amount));

but how to assign it to parent.fundedamount? 但是如何将其分配给parent.fundedamount? Do I need to use group by? 我需要使用分组依据吗?

I have done without linq like this 我没有这样的linq就做了

               foreach (var f in model) {

                            foreach (var fi in f.childlist)
                            {
                                if (fi.parentid== f.Id)
                                {
                                    f.FundedAmount +=  (int)fi.Amount;
                                }
                            }  
                       }

http://prntscr.com/kgzgo4 http://prntscr.com/kgzgo4

please suggest 请建议

Firstly, I group by childlist by parentId to get a collection of distinct id associated with the sum Amount . 首先,我按childlistparentId分组,以获取与总和Amount相关的不同id的集合。

Next, for each group in this collection, I update fundedamount corresponding with the GroupId , means Id of the model. 接下来,对于此集合中的每个组,我更新与GroupId相对应的fundedamount ,即模型的Id

model.childlist.GroupBy(x=> x.parentid).Select(group => new { 
               GroupId = group.Id,
               SumOfGroup = group.Sum(x => x.Amount)
           }).ToList()
             .ForEach(group => model.First(m => m.Id = group.GroupId).fundedamount = group.SumOfGroup )

Why not make FundedAmount a read-only property, and have it return the sum of the Amount in the ChildList? 为什么不将FundedAmount设置为只读属性,并使其返回ChildList中Amount的总和?

public int FundedAmount
{
    get { return ChildList?.Sum(c => c.Amount) ?? 0; }
}

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

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