Sorting a data table based on sort order from another data table

I have 2 data tables, one in which i have my data(D1) with a unique data Id and in another data table(D2) i have the Ids of all the records of my data table(D1) in a particular order.How can i sort my data table(D1) based on the order of Ids in D2.I am using c# asp.net

Answers


You could copy the rows in the ordering table into a Dicationary with an index. Assuming your key field is named Key the code might look like this:

static void Main(string[] args)
{
    var dt = new DataTable("Data");
    var dtOrder = new DataTable("Order");

    // Insert some data here

    int i = 0;
    var orderDict = new Dictionary<object, int>();
    foreach(DataRow row in dtOrder.Rows)
    {
        orderDict.Add(row["Key"], ++i);
    }

    var ordered = dt.Rows.Cast<DataRow>().OrderBy(r => orderDict[r["Key"]]);
}

As I read Peaceman71's comment, I think it is worth mentioning that this is a disconnected approach. Any proper database software will do this for you as well.


It depends on if you want to do this in the code or in the database.

In the database you would join the two tables, such as (MS-SQL/T-SQL):

SELECT D2.Sort, D1.* FROM D2 LEFT JOIN D1 ON D2.ID = D1.ID ORDER BY D2.Sort

In code it depends very much on where you keep the data. DataSet, DataTables etc.


Need Your Help

Laravel 5.1 INSERT if record exists in another table

php mysql validation laravel-5.1

Trying to get my first laravel applications finished, but since I'm quite new to it I cannot figure out a solution.

NHibernate throws "Invalid operation. The connection was closed." exception

asp.net database nhibernate session logging

I have a code piece to record user data in Session_End event of Global.asax. It is working but sometimes it throws "Invalid operation. The connection was closed" exception. I have failed to replicate