合并同一列表中的元素 [英] Combining elements in the same list

查看:40
本文介绍了合并同一列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个来自这样的数据库的列表:

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
    }
};

我想对所有具有相同 TypeID 的元素求和,以便最终结果列表仅包含两个元素:

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
    }
};

如何使用LINQ达到此目的?
干杯
西蒙

How can I achive this using LINQ?
Cheers
Simon

推荐答案

您可以先使用 GroupBy TypeID 进行分组,然后再进行 Sum 在每个组上:

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();

这篇关于合并同一列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆