Blog

Aggregate function in Group By in lambda C#

Lambda

Aggregate function in Group By in lambda C#

Aggregate function in Group By in lambda C#

  1. Create a console application and create a customer class 
				
					public class Customer
{
    public int CustomerCode { get; set; }
    public string CustomerName { get; set; }
    public int TotalOrder { get; set; }
}
				
			

  2. Create a list of customers

				
					var customerList = new List<Customer>()
{
    new Customer{CustomerCode=101,CustomerName = "Steve", TotalOrder = 2, CountryCode="US"},
    new Customer{CustomerCode=102,CustomerName = "Mark", TotalOrder = 4, CountryCode="IN"},
    new Customer{CustomerCode=103,CustomerName = "Bill", TotalOrder = 7, CountryCode="US"},
    new Customer{CustomerCode=104,CustomerName = "Dell",TotalOrder = 6, CountryCode="US"}
};
				
			

  3. Now to get the total orders for each countries, we will do the following

				
					var result = customerList.GroupBy(a => a.CountryCode)
 .Select(a => new
    {
        CountryCode = a.Key,
        TotalOrderValue = a.Sum(b => b.TotalOrder)
    }).ToList();
				
			
dotnetcoaching, dot net tutor

Please comment and share if you like this post and tell us about how we can enhance our posts. Thanks.

Subhajit