Reputation: 3345
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...
Upvotes: 3
Views: 6801
Reputation: 460298
You can use Linq-To-DataSet
:
var orderedRows = from row in dt.AsEnumerable()
orderby row.Field<string>("Name"), row.Field<DateTime>("Date")
select row;
DataTable tblOrdered = orderedRows.CopyToDataTable();
If the Date
column is actually a string column you need to parse it to DateTime
first.
Assuming valid formats:
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.Parse(row.Field<string>("Date"), CultureInfo.InvariantCulture)
orderby row.Field<string>("Name"), date
select row;
Upvotes: 2
Reputation: 706
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";
Upvotes: 2
Reputation: 236328
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.
Upvotes: 4