DataTable merge and sort
I have two DataTables that have the same columns. I would like to append one of these DataTables on to the end of the other and then sort them by date. What is the best way of going about this?
When I try to merge and sort them, like this:
private DataTable mergeAndSortTables(DataTable manualTable, DataTable gpsTable)
{
manualTable.Merge(gpsTable);
manualTable.DefaultView.Sort = "Date DESC";
return manualTable.DefaultView.ToTable();
}
I still end up with rows out of order. What am I doing wrong?
Edit: I also get the exact sam开发者_如何转开发e results with this code:
private DataTable mergeAndSortTables(DataTable manualTable, DataTable gpsTable)
{
manualTable.Merge(gpsTable);
DataView view = manualTable.DefaultView;
view.Sort = "Date DESC";
return view.ToTable();
}
Instead of modifying the default view, create a new view based upon the current table an sort that. This should fix your issue.
You have to assigne the dataview and then work on it.
DefaultView view = manualTable.DefaultView; view.Sort = "Date DESC"; return view.ToTable();
I think the problem might be that Date is a keyword - try ...
manualTable.DefaultView.Sort = "[Date] DESC";
You can use DataTable.Select()
method for sorting although it will return you the DataRow[]. For example, after merging, you can do DataRow[] rows = manualTable.Select("", columnName sortOrder).
You can always convert this DataRow[] to another table and return it.
精彩评论