LINQ - Group DataTable by multiple columns defined at runtime

Using .NET 3.5, I need to group DataTableseveral columns where the column names are contained in IEnumerable.

// column source
IEnumerable<string> columns;
DataTable table;

IEnumerable<IGrouping<object, DataRow>> groupings = table
    .AsEnumerable()
    .GroupBy(row => ???);

It ???will usually be an anonymous type, as described here , but I need to use columnsa column as the source. Is it possible?

+3
source share
1 answer

The easiest way to do this is to create a function that selects the required columns and creates a hash for comparison. I would do something like this:

Func<DataRow, IEnumerable<string>, string> f = (row, cols) => 
    String.Join("|", cols.Select(col => row[col]));

, DataRow IEnumerable<string>. IEnumerable<string> ( ) (cols.Select(col => row[col]))), |. , , .

IEnumerable<IGrouping<object, DataRow>> groupings = table
    .AsEnumerable()
    .GroupBy(row => f(row, columns));

, , . , - , , .

+2

All Articles