I have a generic list of type Element
, for example.
public class Element
{
public string Country { get; set; }
public string City { get; set; }
public int Population { get; set; }
}
With the following data.
var elements = new List<Element>
{
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country A", City = "Barrie2", Population = 12 },
new Element { Country = "Country A", City = "Barrie2", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country D", City = "Essex", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country D", City = "Essex", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 },
new Element { Country = "Country A", City = "Barrie", Population = 12 }
};
Essentially, I'd like a running total of the population grouped by country and city.
Something like.
Country A | Barrie | `running total for Barrie`
Country A | Barrie2 | `running total for Barrie2`
| | `total for Country A`
Country D | Essex | `running total for Essex`
| | `total for Country D`
| | `total for everything`
I couldn't find an extension (I say extension because I plan on using a rollup several times) anywhere so I figure I'd give it a shot. So I started with this simple query.
var groupedElements = elements
.GroupBy(x => new { x.Country, x.City })
.Select(x => new { Country = x.Key, City = x.Select(xx => xx.City), Population = x.Sum(xx => xx.Population) })
.ToList();
This query works as expected so I think I'm on the right track. Next I think I have to figure out which property from groupedElements
is aggregate because that's what we'll be doing a rollup on. How do I accomplish that? Or perhaps I could have a parameter that makes me specify what column I wish to do the aggregate function on.