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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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 idget;set;
int parentidget;set;
int amountget;set;



I want to group child records by parentid and sum the amount and assign it to parent.fundedamount using linq.



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? Do I need to use group by?



I have done without linq like this


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



please suggest




2 Answers
2



Firstly, I group by childlist by parentId to get a collection of distinct id associated with the sum Amount.


childlist


parentId


id


Amount



Next, for each group in this collection, I update fundedamount corresponding with the GroupId, means Id of the model.


fundedamount


GroupId


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?


public int FundedAmount

get return ChildList?.Sum(c => c.Amount) ?? 0;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered