Tuesday, April 7, 2020

Group by in LINQ C#

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.Statex.City } )
                .Select(y => new
                {
                    State= y.Key.State,
                    City = y.Key.City,
                    Count = y.Count()
                }).ToList();

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...