简体   繁体   中英

LINQ: how to aggregate list within object after grouping properties

I have an object ChartObject that contains a list. Then I have a list of ChartObjects that I used LINQ to remove duplicate attributes. But I don't know how to combine each"itemList" property of the ChartObjects.

public class ChartObject
{
    public string Type { get; set; }
    public int Year { get; set; }
    public long Cost { get; set; }
    public List<Items> itemList { get; set; }
}

List<ChartObject> coList = GetItems();

result = coList.GroupBy(i => new { i.Type, i.Year }).Select(g => new ChartObject
{
    Type = g.Key.Type,         
    Year = g.Key.Year,
    Cost = g.Sum(i => i.Cost), 
    itemList = g.Select(i => i.itemList)    //Does not work
}).ToList();

I'm assuming it's not as simple as just casting the itemList as the compiler says and there must be some sort of aggregation to be done?

假设您只想合并组中的所有项目,那么您正在寻找SelectMany ,并且需要调用ToList以获得List<Items>

g.SelectMany(i => i.itemList).ToList();

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