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...
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With