How To Reverse the Order of a C# DataTable without Sorting

Sure, it’s easy to use the built in DataView functionality to sort a DataTable, but what about when you to reverse the order of the data without sorting? On occasion, data can come from a database in a sorted but not sorted manner. For instance, with logs. Ignore timestamps for the time being, sometimes the order in which it is written to the DB is important. Unfortunately, C# does not have a built in method for this. But I’ve written one that will work with any DataTable, enjoy!

 
    public DataTable ReverseRowsInDataTable(DataTable inputTable)
    {
        DataTable outputTable = inputTable.Clone();

        for (int i = inputTable.Rows.Count - 1; i >= 0; i--)
        {
            outputTable.ImportRow(inputTable.Rows[i]);
        }

        return outputTable;
    }
Advertisements

1 Response to “How To Reverse the Order of a C# DataTable without Sorting”


  1. 1 Valters Puzo October 21, 2013 at 1:38 am

    Ty, you saved my day.. Tried all sorting methods to sort table “Id DESC”, none of them worked, when data table all ready sorted “Id ASC”. This is clever solution, thanks again.
    V.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: