Given the following structure...
class Foo {
public string Category { get; set; }
public string Code { get; set; }
public int Quantity { get; set; }
}
I am trying to use Linq to summarise a list of these objects by Category and Code, so that if I provide the following source...
List<Foo> foos = new List<Foo>() {
new Foo {Category = @"A", Code = @"B", Quantity = 1},
new Foo {Category = @"A", Code = @"B", Quantity = 2},
new Foo {Category = @"C", Code = @"D", Quantity = 3},
new Foo {Category = @"C", Code = @"D", Quantity = 4}
};
I end up with a list containing...
Foo {Category = @"A", Code = @"B", Quantity = 3},
Foo {Category = @"C", Code = @"D", Quantity = 7}
(where Quantity is the sum of the original quantities of matching objects).
I know I need to use a combination of the group by
clause and the Sum()
extension methods, I just do not seem to be able to find that correct combination.
Please note, there is no database behind this list, I am doing this purely with objects so extracting the original list including the sum is not an option.
Thanks.