0

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

2
  • Nothing so far. Well it would be easy using foreach but I want to have in with LINQ. Commented Sep 28, 2012 at 9:47
  • Sorry, I forgot link Commented Sep 28, 2012 at 9:48

3 Answers 3

7
list.GroupBy(x=>x.TypeID)
    .Select(x=>new Item(){TypeID=x.Key,Count=x.Sum(y=>y.Count) })
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

Both answers are correct. But Cuong Le war faster... Thx a lot, exactly what I wanted to have.
0

Linq extension method Union.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.