简体   繁体   中英

Assigning the result of group by to items in a list with linq

I have an

IEnumerable<typeA> result;

from this result I need to get sum group by some id.

So I have the query

 var groupeddata = from data in result
                      group data by data.Title
                      into grouped
                      select new { intid= grouped.Key,
                                   expsum= grouped.Sum(x=>x.expnum)};

now this expsum I need to assign to the items of result where typeA.id is same as intid. Now how to do this assignment?

The simplest approach would probably be to use a dictionary:

var sumDictionary = query.ToDictionary(pair => pair.intid, pair => pair.expsum);
foreach (var item in result)
{
    // We don't know which property you actually want to assign to
    item.Sum = sumDictionary[item.id];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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