I have a DataTable
that looks like below;
| ID | ItemIndex | ItemValue
ce895bd9-9a92-44bd-8d79-986f991154a9 1 3
ae7d714e-a457-41a8-8bb4-b5a0471c3d2f 2 2
a774dff3-acc0-4f50-a211-a775e28dcae3 2 1
292bbd50-290b-4511-9e4e-2e74e3ebe273 3 2
ae7d714e-a457-41a8-8bb3-b5a0471c3d22 3 1
I want to sort this table by ItemIndex
first, then sort the sorted table by ItemValue
.
How can I achieve this?
Edit: after sorting, I want my table like below;
| ID | ItemIndex | ItemValue
ce895bd9-9a92-44bd-8d79-986f991154a9 1 3
a774dff3-acc0-4f50-a211-a775e28dcae3 2 1
ae7d714e-a457-41a8-8bb4-b5a0471c3d2f 2 2
ae7d714e-a457-41a8-8bb3-b5a0471c3d22 3 1
292bbd50-290b-4511-9e4e-2e74e3ebe273 3 2
The DataView provides several ways of sorting and filtering data in a DataTable: You can use the Sort property to specify single or multiple column sort orders and include ASC (ascending) and DESC (descending) parameters.
Sort DataTable With the DataView. We can set the sort column of our datatable by specifying the column name like DataView. Sort = "Col_name" . By default, this method sorts the datatable in ascending order. We can specify desc after the column name to sort the datatable in descending order.
You can use LINQ to DataSet/DataTable
var newDataTable = yourtable.AsEnumerable()
.OrderBy(r=> r.Field<int>("ItemIndex"))
.ThenBy(r=> r.Field<int>("ItemValue"))
.CopyToDataTable();
Create a DataView and use the Sort Property:
DataView dv = new DataView(dt);
dv.Sort = "ItemIndex, ItemValue";
e.g.
foreach (DataRowView row in dv) {
Console.WriteLine(" {0} \t {1}", row["ItemIndex"], row["ItemValue"]);
}
For more information, check out MDSN for a more thorough example:
http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx
On the datatable object, just get the defaultview object and set the sort.
dataTable.DefaultView.Sort = "ItemIndex, ItemValue";
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