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));