Group by multiple columns

How to group multiple columns in LINQ

Similar in SQL:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>

How to convert it to LINQ:

QuantityBreakdown
(
    MaterialID int,
    ProductID int,
    Quantity float
)

INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

#1 building

Although this question asks about grouping properties by class, if you want to group by more than one column for an ADO object, such as a DataTable, you must assign the new item to the variable:

EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
                        .Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
                    var Dups = ClientProfiles.AsParallel()
                        .GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
                        .Where(z => z.Count() > 1)
                        .Select(z => z);

#2 building

You can also use tuple < > for strong type grouping.

from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),
}

#3 building

For group by multiple columns, use this method instead

GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new 
{ 
  Key1 = key.Column1,
  Key2 = key.Column2,
  Result = group.ToList() 
});

In the same way, you can add Column3, Column4, and so on.

#4 building

var Results= query.GroupBy(f => new { /* add members here */  });

#5 building

Starting with C 7, you can also use value tuples:

group x by (x.Column1, x.Column2)

Or

.GroupBy(x => (x.Column1, x.Column2))

Keywords: SQL

Added by AlanG on Sun, 15 Dec 2019 16:15:05 +0200