How to group by multiple columns using LINQ
By FoxLearn 12/12/2024 1:08:34 AM 26
In LINQ, you can group by multiple columns using the group by clause in combination with anonymous types.
Group by Multiple Columns in LINQ
For example, Use an anonymous type.
group x by new { x.Column1, x.Column2 }
To group the products by both Category
and Brand
, you can use an anonymous object as the key in the group by
clause:
var query = (from t in Transactions group t by new { t.MaterialID, t.ProductID } into grp select new { grp.Key.MaterialID, grp.Key.ProductID, Quantity = grp.Sum(t => t.Quantity) }).ToList();
Since C# 7 you can also use value tuples:
A Value Tuple is a lightweight and efficient way to store multiple values without creating a full-fledged class or struct. It can be especially useful when you need to group by multiple columns.
group x by (x.Column1, x.Column2)
or
.GroupBy(x => (x.Column1, x.Column2))
For example:
var query = Transactions .GroupBy(t => (t.MaterialID, t.ProductID)) .Select(grp => new { grp.Key.MaterialID, grp.Key.ProductID, Quantity = grp.Sum(t => t.Quantity) }) .ToList();
or
// declarative query syntax var result = from x in Transactions group x by (x.MaterialID, x.ProductID) into g select (g.Key.MaterialID, g.Key.ProductID, QuantitySum: g.Sum(x => x.Quantity));
- How to get index of element in array C# LINQ
- How to get the index of an element in C# LINQ
- Using LINQ's Distinct() on a Specific Property
- Difference Between Select and SelectMany in LINQ
- Group by in LINQ
- Using LINQ to remove elements from a List<T>
- Using LINQ to Query DataTables
- IEnumerable<T> vs IQueryable<T>
Categories
Popular Posts
Modular Admin Template
11/14/2024
Star Admin Dashboard Template
11/17/2024
Gentella Admin Template
11/14/2024
Material Lite Admin Template
11/14/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024