Simon Linder
Simon Linder

Reputation: 3428

Combining elements in the same list

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

Upvotes: 0

Views: 130

Answers (3)

cuongle
cuongle

Reputation: 75296

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

Upvotes: 5

Sender
Sender

Reputation: 6858

Linq extension method Union.

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

Upvotes: 0

L.B
L.B

Reputation: 116098

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

Upvotes: 7

Related Questions