I have a generic list of types 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 }
};
In fact, I would like the total population to be grouped by country and city.
Sort of.
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 could not find the extension (I say the extension because I plan to use the cumulative file several times), so I believe that I would give it a chance. 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. Then I think that I need to figure out which property of groupedElementsis aggregated, because that will be what we will do. How to do it? Or maybe I could have a parameter that forces me to indicate in which column I want to enable the aggregate function.