Mehmet Ince
Mehmet Ince

Reputation: 4179

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

Upvotes: 30

Views: 84452

Answers (7)

DarkPh03n1X
DarkPh03n1X

Reputation: 680

Here is my take, given the helpful comments of others here.

DataView dataView = new DataView(dataTable);//datatable to dataview
dataView.Sort = "columnName1 ASC, columnName2 DESC";//string that contains the column name  followed by "ASC" (ascending) or "DESC" (descending)
dataTable = dataView.ToTable();//push the chages back to the datatable

Upvotes: 4

Amit Kumar Verma
Amit Kumar Verma

Reputation: 367

Alternatively you can use that

DataView oDataSet;
oDataSet.Tables[0].DefaultView.Sort = "Column1 ASC ";

Upvotes: 3

user5940155
user5940155

Reputation: 19

_UserAuditTrailTable.DefaultView.Sort = sortExpression;

Upvotes: 1

Ty Petrice
Ty Petrice

Reputation: 1839

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

dataTable.DefaultView.Sort = "ItemIndex, ItemValue";

Upvotes: 27

Nishant
Nishant

Reputation: 306

By creating dataview

var dataView = new DataView(dataTable);
dataView.Sort = "ItemIndex ASC, ItemValue ASC"

Here dataTable is table you want to sort

Upvotes: 12

George Johnston
George Johnston

Reputation: 32258

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

Upvotes: 32

Habib
Habib

Reputation: 223217

You can use LINQ to DataSet/DataTable

var newDataTable = yourtable.AsEnumerable()
                   .OrderBy(r=> r.Field<int>("ItemIndex"))
                   .ThenBy(r=> r.Field<int>("ItemValue"))  
                   .CopyToDataTable();

Upvotes: 49

Related Questions