In SQL, GROUP BY is used in combination with aggregate functions like COUNT(), SUM(), AVG(), MAX(), and MIN() to perform operations on each group.
Example
Suppose we have a table called Sales with columns SalesPerson and SalesAmount. To get the total sales amount for each salesperson, you would use as following.
SELECT SalesPerson, SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY SalesPerson;
In LINQ, GroupBy is used to achieve similar grouping operations. You typically use it in combination with aggregate methods to perform calculations on each group.
Example
Assuming you have a list of Sale objects in C#.
public class Sale
{
public string SalesPerson { get; set; }
public decimal SalesAmount { get; set; }
}
var sales = new List<Sale>
{
new Sale { SalesPerson = "Alice", SalesAmount = 1000 },
new Sale { SalesPerson = "Bob", SalesAmount = 500 },
new Sale { SalesPerson = "Alice", SalesAmount = 1500 },
new Sale { SalesPerson = "Bob", SalesAmount = 300 }
};
var groupedSales = sales
.GroupBy(s => s.SalesPerson)
.Select(g => new
{
SalesPerson = g.Key,
TotalSales = g.Sum(s => s.SalesAmount)
});
foreach (var group in groupedSales)
{
Console.WriteLine($"SalesPerson: {group.SalesPerson}, TotalSales: {group.TotalSales}");
}