You can use the LINQ GroupBy method to group the data by a particular column and then use aggregate functions (like Sum, Average, Count, etc.) to calculate the desired values for each group. Here's an example:
Assume we have a list of sales data that includes the salesperson, the month, and the sales amount:
List<SalesData> salesData = new List<SalesData>()
{
new SalesData("John", "January", 1000),
new SalesData("John", "February", 2000),
new SalesData("Mary", "January", 1500),
new SalesData("Mary", "February", 2500)
};
To retrieve the total sales amount for each salesperson, we can use GroupBy and Sum like this:
var salesByPerson = salesData
.GroupBy(sd => sd.Salesperson)
.Select(g => new
{
Salesperson = g.Key,
TotalSales = g.Sum(sd => sd.SalesAmount)
});
This will give us a new anonymous type that includes the Salesperson and TotalSales for each group:
Salesperson TotalSales
----------- ----------
John 3000
Mary 4000
You can add more aggregate functions as needed (e.g. Average, Count, Min, Max, etc.) and include multiple columns in the grouping if necessary.
Asked: 2021-06-24 11:00:00 +0000
Seen: 14 times
Last updated: Dec 24 '21