Taşkın Binbir
2 min readMay 1, 2022

--

How to use better GroupBy in LINQ ?

Hello everbody,

We often use LINQ. It is a very advanced query technology. I want to explain with one example.

First of all, our models;

public class UpdateBasketRequest{public string BuyerId { get; set; }public IEnumerable<UpdateBasketRequestItemData> Items { get; set; }}public class UpdateBasketRequestItemData{public string Id { get; set; }          // Basket idpublic int ProductId { get; set; }      // Catalog item idpublic int Quantity { get; set; }       // Quantitypublic UpdateBasketRequestItemData(string Id, int ProductId, int Quantity){this.Id = Id;this.ProductId = ProductId;this.Quantity = Quantity;}

Main part is:

UpdateBasketRequest data = new UpdateBasketRequest();data.BuyerId = "1";data.Items = new List<UpdateBasketRequestItemData> {new UpdateBasketRequestItemData("1", 1, 2),new UpdateBasketRequestItemData("1", 2, 2),new UpdateBasketRequestItemData("1", 3, 5),new UpdateBasketRequestItemData("2", 2, 5) };//Id, ProductId, Quantityvar itemsCalculated = data.Items.GroupBy(x => x.ProductId, x => x, (k, i) => new { productId = k, items = i }).Select(groupedItem =>{var item = groupedItem.items.First();item.Quantity = groupedItem.items.Sum(i => i.Quantity);return item;});foreach (var i in itemsCalculated){Console.WriteLine(i.Id);Console.WriteLine(i.ProductId);Console.WriteLine(i.Quantity);Console.WriteLine("*****");}

Most basically, any buyer may has multiple basket, could put any product also each product could be multiple.

There are a buyer has in our example.

This buyer has 2 basket.

First basket has 2 products of the product number 1, 2 products of the product number 2 and 5 products of the product number 3.

Second basket has 5 products of the product number 2.

All items do group by productId. When we group with product id, result is products’ id and products’ quantitys.

product id:1
Quantity: 2
*****
product id:2
Quantity: 7
*****
product id:3
Quantity: 5
*****

Good luck.

This example on my github; https://github.com/taskinbinbir/LinqGroupByApp

You can follow my list about of Entity Framework and LINQ for more; https://taskinbinbir.medium.com/list/entity-framework-0a2b9ee4b7c3

Referance; https://github.com/dotnet-architecture/eShopOnContainers

--

--