Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort DataTable by two columns in c#

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
like image 641
Mehmet Ince Avatar asked Apr 30 '13 14:04

Mehmet Ince


People also ask

How do you sort and filter data using DataView?

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.

How do you sort a DataTable?

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.


3 Answers

You can use LINQ to DataSet/DataTable

var newDataTable = yourtable.AsEnumerable()
                   .OrderBy(r=> r.Field<int>("ItemIndex"))
                   .ThenBy(r=> r.Field<int>("ItemValue"))  
                   .CopyToDataTable();
like image 106
Habib Avatar answered Oct 03 '22 01:10

Habib


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

like image 23
George Johnston Avatar answered Oct 03 '22 00:10

George Johnston


On the datatable object, just get the defaultview object and set the sort.

dataTable.DefaultView.Sort = "ItemIndex, ItemValue";
like image 30
Ty Petrice Avatar answered Oct 03 '22 00:10

Ty Petrice