Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group DataTable and sort each group by a field?

Tags:

c#

datatable

I have a DataTable that looks like below;

| ItemName | ItemNo |   ItemValue
     A         2            3,1
     B         1            2,2
     C         3            1,5
     A         2            2,0
     B         1            1,4
     A         2            2,7
     C         3            1,3
     C         3            2,1
     B         1            1,9

I want to group above DataTable by ItemName and sort these groups by ItemNo first, then sort the each sorted group inside by ItemValue.

How can I achieve this?

Note: after sorting, I want my table like below;

| ItemName | ItemNo |   ItemValue
     B         1            1,4
     B         1            1,9
     B         1            2,2
     A         2            2,0
     A         2            2,7
     A         2            3,1
     C         3            1,3
     C         3            1,5
     C         3            2,1
like image 672
Mehmet Ince Avatar asked May 29 '13 07:05

Mehmet Ince


2 Answers

table = table.AsEnumerable()
             .GroupBy(r => r.Field<string>("ItemName"))
             .OrderBy(g => g.Max(r => r.Field<int>("ItemNo")))
             .SelectMany(g => g.OrderBy(r => r.Field<double>("ItemValue")))
             .CopyToDataTable();

I want to group above DataTable by ItemName and sort these groups by ItemNo first, then sort the each sorted group inside by ItemValue.

But ItemNo is not part of the goup-key, so how do you want to sort the groups by ItemNo if the values are different in each group(as opposed to your sample data)? By max/min/avg value? I have used Max to demonstrate one approach.

Edit So actually both columns belong to the same key, then i would use an anonymous type as grouping key that contains both columns, then it's even clearer:

table = table.AsEnumerable()
             .GroupBy(r => new
             { 
                 ItemName = r.Field<string>("ItemName"),
                 ItemNo   = r.Field<int>("ItemNo") 
             })
             .OrderBy(g => g.Key.ItemNo)
             .SelectMany(g => g.OrderBy(r => r.Field<double>("ItemValue")))
             .CopyToDataTable();
like image 65
Tim Schmelter Avatar answered Oct 20 '22 00:10

Tim Schmelter


You can define a SortYourDataTable method like;

public static DataTable SortYourDataTable(DataTable dt, string column)
{
    dt.DefaultView.Sort = column;
    dt = dt.DefaultView.ToTable();
    return dt;
}

Then call it;

SortYourDataTable(SortYourDataTable(SortYourDataTable(dt, "ItemNo"), "ItemName"), "ItemValue");
like image 28
Soner Gönül Avatar answered Oct 19 '22 22:10

Soner Gönül