Group by and Sort data descending

Hi,
I have a Data table like below,

Dept, Total Seats
Medical, 55
Engineering,101
Medical, 100
Medical,45
Medical,23
Engineering,200

I want the data to be grouped by Department and Sorted Descending based on Total Seats Column like below,

Dept, Total Seats
Medical, 100
Medical, 55
Medical,45
Medical,23
Engineering,200
Engineering,101

I need a LinQ for this.

Thanks in advance

@besakkiappan46,

Try this LINQ query:

dt.AsEnumerable.GroupBy(Function(r) r("Dept").ToString()).SelectMany(Function(g) g.OrderBy(Function(r) r("Total Seats"))).CopyToDataTable

Thanks,
Ashok :slight_smile:

1 Like

@besakkiappan46

Just a add on to the above reply nothing much

dt.AsEnumerable.GroupBy(Function(a) a(0).ToString).SelectMany(Function(b) b.OrderByDescending(Function(c) c(1).ToString)).copytodatatable
1 Like

Thank you. It worked. Just added “orderbyDescending” to it

1 Like

@ashokkarale @Shiva_Nikhil Any reason why Descending alone isn’t happening? It did grouped properly.

@besakkiappan46,

Try this modified LINQ

dt.AsEnumerable _
    .GroupBy(Function(r) r("Dept").ToString()) _
    .OrderBy(Function(g) g.Key) _
    .SelectMany(Function(g) g.OrderBy(Function(r) Convert.ToInt32(r("Total Seats")))) _
    .CopyToDataTable()

Thanks,
Ashok :slight_smile:

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.