2

I have a list of objects which looks like this

class foo
{
    string name;
    int number;
}

var myList = new List<foo>();

myList is propagated from an SQLite database and ordered by the name. There is no reason why there cannot be more than one entry with the same name, so you can have

myList[ = {"paul", 1234},{"paul", 12}, {"becki",99},{"becki", 33}...

I am trying to create a new list based on myList that contains a single instance of the name, and with number to be the total of the numbers using LINQ.

I'm thinking that something like

var myNewList = new List<foo>();
var names = myList.Select(t=>t.name).Distinct().ToList();
foreach(var n in names)
    myNewList.Add(new foo() {name = n, number = myList.Where(t=>t.name == n).Sum(t=>t.number)});

Is there a simpler way to do this?

Nodoid
  • 1,449
  • 3
  • 24
  • 42

1 Answers1

2

Group the items by name then project with the Key and sum the values:

var result = myList.GroupBy(f => f.name)
                   .Select(g => new foo
                   {
                       name = g.Key,
                       number = g.Sum(f => f.number)
                   }).ToList();
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174