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.
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
Asked: 2021-06-24 11:00:00 +0000
Seen: 14 times
Last updated: Dec 24 '21
How can the columns be transformed into a multi-level structure?
How to arrange columns in a Flutter datatable?
What is the method to obtain a count from specific columns while disregarding the rest?
What are the steps to utilize a for loop for generating and populating columns?
Is it possible that there are some missing values when combining across columns?
How can the precision be varied across different columns in pandas?