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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use LINQ to DataSet/DataTable

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

Method 2

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

Method 3

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

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

Method 4

By creating dataview

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

Here dataTable is table you want to sort

Method 5

Alternatively you can use that

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

Method 6

_UserAuditTrailTable.DefaultView.Sort = sortExpression;

Method 7

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x