Not logged in - Login

Using Linq to Group by Columns

Some samples on how to use Linq to build queries that group by columns.

The following illustrates how to use Linq to group a strongly typed data table by a single column.

// build a Linq query to group a strongly typed data table by a single column.
var grpTest1 = from a in tbl1
               group a by a.colA into g
               select g;

// iterate through each row in the result set
foreach (var rowGrp in grpTest1)
{
   // the 'Key' property returns the grouped by column, in this case, 'colA'
   string temp = rowGrp.Key;            
}

The following illustrates how to use Linq to group a strongly typed data table by multiple columns.

// build a Linq query to group a strongly typed data table by multiple columns
var grpTest2 = from a in tbl1
              group a by new
              {
                 fldA = a.colA,
                 fldB = a.colB,
                 fldC = a.colC
              } into g
              select g;

// iterate through each row in the result set
foreach (var rowGrp2 in grpTest2)
{
   // in this case, the 'Key' property has sub-properties that hold the values of the multiple columns.
   string temp1 = rowGrp2.Key.fldA;
   string temp2 = rowGrp2.Key.fldB;
   string temp3 = rowGrp2.Key.fldC;
}

The following illustrates how to group a data table by a single column.

Note: the AsEnumerable() extension requires 'using System.Data;' to be added to the top of the file.

// build a Linq query to group a data table by a single column
var grpTest3 = from a in tbl2.AsEnumerable()
               group a by a.Field<int>("RowID") into g
               select g;

// iterate through each row in the result set
foreach (var rowGrp3 in grpTest3)
{
   // the 'Key' property returns the grouped by column, in this case, 'RowID'
   int test1 = rowGrp3.Key;
}

The following illustrates how to group a data table by multiple columns.

// build a Linq query to group a data table by multiple columns
var grpTest4 = from a in tbl2.AsEnumerable()
               group a by new
               {
                  CustName = a.Field<string>("CustomerName"),
                  CustAddr = a.Field<string>("CustomerAddress")
               } into g
               select g;

// iterate through each row in the result set
foreach (var rowGrp4 in grpTest4)
{
   // in this case, the 'Key' property has sub-properties that hold the values of the multiple columns.
   string custName = rowGrp4.Key.CustName;
   string custAddr = rowGrp4.Key.CustAddr;
}