Q:

Manipulate a collection to produce a condensed version

I'm currently stumped on a small piece of functionality that I can't seem to figure out. 
Firstly I have a Stock class that looks as follows:
public class Stock
{
    public int Id;
    public int LocationId;
    public int Quantity;
}

Stock logs are returned from the database which are produced from another piece of functionality.  The log is represented as a List<Stock> collection - however I need to add the Quantity property of each object of the same ID and LocationID combination, for example:

Original Data Set:
ID: 1    Location: 1    Quantity: 20
ID: 1    Location: 2    Quantity: 30
ID: 1    Location: 1    Quantity: 30
ID: 2    Location: 2    Quantity: 20
ID: 1    Location: 2    Quantity: 30
ID: 1    Location: 1    Quantity: 100

Should return:

Condensed Data Set:
ID: 1    Location: 1    Quantity: 150
ID: 1    Location: 2    Quantity: 60
ID: 2    Location: 2    Quantity: 20

To reiterate: The data set is dynamically returned from a database, there is no guarantee that there will be every ID & LocationID combination and I need the resultant data set to be unique on a compound key of ID and LocationID. 
Not sure about the most effective way of going about this and it's holding back my progress with the project, any advice or approaches would be much appreciated.  I'm kind of thinking this is a knowledge gap really but I've not been able to find anything appropriate / that fits my requirements (it's quite an odd requirement I guess). 
Many thanks,
Andy

A:

It would be better to do this on the database but you can also use GroupBy to achieve the exact same effect:
public class Stock
{
    public int Id;
    public int LocationId;
    public int Quantity;
}

static void Main(string[] args)
{
    var list = new List<Stock>()
        {
            new Stock(){ Id = 1, LocationId = 1, Quantity = 20},
            new Stock(){ Id = 1, LocationId = 2, Quantity = 30},
            new Stock(){ Id = 1, LocationId = 1, Quantity = 30},
            new Stock(){ Id = 2, LocationId = 2, Quantity = 20},
            new Stock(){ Id = 1, LocationId = 2, Quantity = 30},
            new Stock(){ Id = 1, LocationId = 1, Quantity = 100},

        };

    var grouped = list. GroupBy(c => new {Id = c.Id, LocationId = c.LocationId})
            .Select(g => new 
                 { 
                      Id = g.Key. Id, 
                      LocationId = g.Key. LocationId, 
                      Quantity = g.Sum(a => a.Quantity) 
                  });
    foreach(var group in grouped. OrderBy(c => c.Id))
    {
        Console. WriteLine("Id:{0} - LocationId:{1} - Quantity:{2}", group. Id, 
                 group. LocationId, group. Quantity);
    }
}

