简体   繁体   中英

List c# distinct by item and sum other items

Imagine a list of objects:

public class Foo
{
    public string Name {get; set;}
    public int Total {get; set;}
}

And now, my list contains 3 objects:

new Foo {Name="object", Total=3};
new Foo {Name="object", Total=7};
new Foo {Name="object", Total=5};

How to distinct by the name and sum the totals? ie The List will have just one object:

new Foo {Name="object", Total=15};

Thanks in advance!

You can do this:

var newTotalList = yourList.GroupBy(x => x.Name)
    .Select(x => new
        {
            Name = x.Key,
            Total = x.Sum(y => y.Total)
        })
    .ToList();

What this code does is, simply, first group the elements by name, and then sum the Total fields of all the elements inside the group.

You should be able to use grouping.

var groupedList = (from ol in objectList

                    group ol by ol.Name
                        into grp
                        select new foo
                        {
                            Name = grp.Key,
                            Total= grp.Sum(ex => ex.Total),
                            City = grp.Select(ex => ex.City).FirstOrDefault(),
                            Country = grp.Select(ex => ex.Country ).FirstOrDefault(),
                            Phone = grp.Select(ex => ex.Phone).FirstOrDefault()
                        }
    ).ToList();

Try this:

List<Object> list = ... // make a list somehow
var totalsPerName = list
    .GroupBy(o => o.Name)
    .Select(group => new Object { Name = group.Key, Total = group.Sum(o => o.Total) })

You can group by Name and then just sum up by Total :

var l = new List<Object>
{
    new Object {Name="object", Total=3},
    new Object {Name="object", Total=7},
    new Object {Name="object", Total=5}
};

var result = l.GroupBy(o => o.Name)
              .Select (grp => new Object 
                            { 
                                Name = grp.Key, 
                                Total = grp.Sum(o => o.Total)
                            });

result is now:

在此处输入图片说明

Group your elements by Name, and then for each group, select a new object whose name is name value grouped by for this group, and Total is the sum of all Totals in the group:

var groupdObject =list
    .GroupBy(o =>o.Name)
    .Select(g => 
       new 
       {
         Name = g.Key, 
         Total = g.Sum(o=>o.Total)
       });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM