Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort DataTable based on multiple column?

I have DataTable

Name  Date
bbb   01/01/2011
bbb   01/01/2012
aaa   01/01/2010
aaa   01/01/2011
bbb   01/01/2013
aaa   01/01/2012
bbb   01/01/2010
ccc   01/01/2010
aaa   01/01/2013
ccc   01/01/2012
ccc   01/01/2011

I need sort this table sort by name and every name by date:

Name  Date
aaa   01/01/2010
aaa   01/01/2011
aaa   01/01/2012
aaa   01/01/2013
bbb   01/01/2010
bbb   01/01/2011
bbb   01/01/2012
bbb   01/01/2013
ccc   01/01/2010
ccc   01/01/2011
ccc   01/01/2012

How to sort DataTable in c#?

I've tried the following:

   DataView dv = dt.DefaultView;
   dv.Sort = "col1 desc";
   DataTable sortedDT = dv.ToTable();

but this sort only by 1 column...

like image 320
Bryuk Avatar asked Jul 04 '26 03:07

Bryuk


2 Answers

You can use LINQ to DataSet

var sortedDT = dt.AsEnumerable()
                 .OrderBy(r => r.Field<string>("Name"))
                 .ThenBy(r => r.Field<DateTime>("Date"))
                 .CopyToDataTable();

Use CopyToDataTable method to create new DataTable from ordered rows.

like image 139
Sergey Berezovskiy Avatar answered Jul 05 '26 17:07

Sergey Berezovskiy


http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx

All you need to do is add a comma between the columns in the dv.Sort line.

To clarify

dv.Sort = "Name, Date";
like image 37
neilh Avatar answered Jul 05 '26 17:07

neilh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!