Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.