Archive for February, 2012

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