thecodeexplorer
thecodeexplorer

Reputation: 373

Group DataTable by column and convert to List<DataTable>

I have a DataTable that looks like the below:

Category | Amount
Food     | 10
Drink    | 20
Clothes  | 50
Drink    | 30
Food     | 40
Clothes  | 5

I want to group it by the Category column and convert each similar grouping into a DataTable and place it inside a List. So I need to have 3 DataTables like the below:

DataTable 1

Category | Amount
Food     | 10
Food     | 40

DataTable 2

Category | Amount
Drink    | 20
Drink    | 30

DataTable 3

Category | Amount
Clothes  | 50
Clothes  | 5

Any advice on how to achieve the above? I can only find questions that want to have an output of 1 DataTable.

Upvotes: 0

Views: 1158

Answers (1)

vc 74
vc 74

Reputation: 38179

You can use Linq to objects (and Linq to Dataset) this way

List<DataTable> tablesByCategory = 
    table.AsEnumerable().
          GroupBy(r => r.Field<double>("Category")).
          Select(g => 
          {
              DataTable dt = table.Clone();

              foreach (DataRow r in g)
              {
                  dt.ImportRow(r);
              }

              return dt;
          }).ToList();

Upvotes: 3

Related Questions