How to: Sort and Reverse a DataTable

In order to sort/order the rows of a DataTable, we need to pass them through to an array of DataRow and access the DataTable’s “select” method.

If the DataTable is called dtDocuments.

 To order:

DataRow[] drDocuments = dtDocuments.Select(null, “nameOfColumn”);

The above will create an array of DataRow. The members of the array will be sorted against the DataTable column whose name is specified in the quotes (ie. nameOfColumn). The null before the name of the column indicates that there will NOT be a filter applied to the results. That means that ALL rows of the DataTable will make it to the Array.

Now, if that is the way to sort a DataTable, shouldn’t the way to invert/reverse it be similar? Apparently, it is. The SQL “DESC” will do the trick. So, for the same DataTable and Array:

 To reverse:

DataRow[] drDocuments = dtDocuments.Select(null, “nameOfColumn DESC”);

The above will pass all the rows of the DataTable to the Array, in the reverse order (goes without saying that they will still be sorted against the column “nameOfColumn”).

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.