In LINQ, Group By method is used to group of source element by using single or more than one property of element.
Here is an example of Group by:
In below LINQ Query, the order records is grouped by customer ID and returns total count of order for each customer.
var result = _dbContext.Orders.GroupBy(x => x.CustomerID)
.Select(y => new
{
CustomerID = y.Key,
Count = y.Count()
}).ToList();
Group by on multiple Columns:
In below LINQ Query, the order records is grouped by State and City (more than one columns) and it returns the count of order for each City.
var result = _dbContext.Orders.GroupBy(x => new { x.State, x.City } )
.Select(y => new
{
State= y.Key.State,
City = y.Key.City,
Count = y.Count()
}).ToList();
No comments:
Post a Comment