Christopher
Christopher

Reputation: 2057

Summarize list by property

I have a list of objects like this:

List<ClassName> list = new List<ClassName>();
list.Add(new ClassName()
{
    Name = 1,
    Amount = 5
});
list.Add(new ClassName()
{
    Name = 2,
    Amount = 10
});
list.Add(new ClassName()
{
    Name = 1,
    Amount = 20
});
list.Add(new ClassName()
{
    Name = 3,
    Amount = 10
});
list.Add(new ClassName()
{
    Name = 3,
    Amount = 15
});

Now I would like to summarize this list by the property Name. The result should contain one entry for every Name and the sum of Amount of the entries with the same Name. So this would be the expected result:

List<ClassName> list = new List<ClassName>();
list.Add(new ClassName()
{
    Name = 1,
    Amount = 25
});
list.Add(new ClassName()
{
    Name = 2,
    Amount = 10
});
list.Add(new ClassName()
{
    Name = 3,
    Amount = 25
});

How can I archive this?

Upvotes: 0

Views: 703

Answers (3)

Pavel Bakshy
Pavel Bakshy

Reputation: 7747

Do it via LINQ:

var result = list.GroupBy(x => x.Name)
    .Select(x => new ClassName { Name = x.Key, Amount = x.Sum(i => i.Amount) })
    .ToList();

Read more about LINQ here: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

Upvotes: 2

Letterman
Letterman

Reputation: 4206

var result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount));

OR

List<MyClass> result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount)).ToList();

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

 var lst = list.GroupBy(g = > g.Name).Select(t = > new
 ClassName()
 {
     Amount = t.Sum(s=>s.Amount), Name = t.Key
 }).ToList();

Upvotes: 1

Related Questions