LINQ: groupby and Join together
I need set of products per Category as shown below
LINQ: groupby and Join together
I need set of products per Category as shown below
Category: Electronics
Laptop
Monitor
Category: Peripherals
Mouse
Keyboard
Category: Furniture
where the data is given as a separate table for products and category
List<Product> products = new List<Product>
{
new Product { ProductId = 1, Name = "Laptop", Price = 1200m, CategoryId = 1 },
new Product { ProductId = 2, Name = "Mouse", Price = 25m, CategoryId = 2 },
new Product { ProductId = 3, Name = "Keyboard", Price = 75m, CategoryId = 2 },
new Product { ProductId = 4, Name = "Monitor", Price = 300m, CategoryId = 1 },
new Product { ProductId = 5, Name = "Webcam", Price = 50m, CategoryId = 4 },
new Product { ProductId = 6, Name = "Desk", Price = 400m, CategoryId = 3 }
};
List<Category> categories = new List<Category>
{
new Category { CategoryId = 1, Name = "Electronics" },
new Category { CategoryId = 2, Name = "Peripherals" },
new Category { CategoryId = 3, Name = "Furniture" }
};
We can do it using Linq query as below
var result = (from c in categories
join p in products on c.CategoryId equals p.CategoryId
group new { c, p } by new { c.CategoryId, c.Name } into g
select new
{
CategoryId = g.Key.CategoryId,
CategoryName = g.Key.Name,
ProductNames = g.Select(x => x.p.Name).ToList()
}).ToDictionary(x => x.CategoryName, x => x.ProductNames);
foreach (var item in result)
{
Console.WriteLine($"Category: {item.Key}");
foreach (var item2 in item.Value)
{
Console.WriteLine($" {item2}");
}
}
Similarly, we can so this using Linq Method: GroupJoin
var result = categories.GroupJoin(
products,
category => category.CategoryId,
product => product.CategoryId,
(category, prodCollection) => new
{
CategoryName = category.Name,
Products = prodCollection.Select(p => p.Name).ToList()
});
foreach (var item in result)
{
Console.WriteLine($"Category: {item.CategoryName}");
foreach (var prod in item.Products)
{
Console.WriteLine($" {prod}");
}
} 메타데이터
- post_id
- 7f6f9b63daaf
- slug
- linq-groupby-and-join-together-7f6f9b63daaf
- url
- https://medium.com/@abhineet_kumar/linq-groupby-and-join-together-7f6f9b63daaf
- canonical_url
- https://medium.com/@abhineet_kumar/linq-groupby-and-join-together-7f6f9b63daaf
- author_url
- https://medium.com/@abhineet_kumar
- status
- ok
- fetched_at
- 2026-08-04 17:46:59