Combining elements in the same list

自作多情 提交于 2021-02-08 11:08:10

问题


suppose I have a list that comes from a database like this:

List<Item> list =
{
    new Item
    {
        TypeID = 2,
        Count = 5
    },
    new Item
    {
        TypeID = 2,
        Count = 7
    },
    new Item
    {
        TypeID = 5,
        Count = 2
    }
};

I would like to sum up all elements with the same TypeID so that I have a final result list with two elements only:

List<Item> list =
{
    new Item
    {
        TypeID = 2,
        Count = 12
    },
    new Item
    {
        TypeID = 5,
        Count = 2
    }
};

How can I achive this using LINQ?
Cheers
Simon


回答1:


You can use GroupBy to group by TypeID first and then do Sum on each group:

var result = list.GroupBy(x => x.TypeID)
                 .Select(g => new Item() { 
                                  TypeId = g.Key, 
                                  Count = g.Sum(x => x.Count)
                         })
                 .ToList();



回答2:


list.GroupBy(x=>x.TypeID)
    .Select(x=>new Item(){TypeID=x.Key,Count=x.Sum(y=>y.Count) })
    .ToList();



回答3:


Linq extension method Union.

var mergedList = list1.Union(list2).ToList();


来源:https://stackoverflow.com/questions/12637448/combining-elements-in-the-same-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!