Ask Your Question
0

How can I use LINQ to retrieve numerous aggregated columns at once?

asked 2021-06-24 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-12-24 03:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-24 11:00:00 +0000

Seen: 14 times

Last updated: Dec 24 '21