Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort DataTable by Custom List Order

Tags:

c#

.net

I'm looking to sort a DataTable based on a particular column and an existing sorted list. This is what I came up with so far:

public DataTable SortByID(DataTable table, string columnName, List<int> ids)
{
    DataTable result = table.Clone();
    foreach (int id in ids)
    {
        foreach(DataRow row in table.Rows)
        {
            if (Convert.ToInt32(row[columnName]) == id)
            {
                result.Rows.Add(row.ItemArray);
                break;
            }
        }
    }
    return result;
}

This works, but I think that there might be some other solution that performs better.

like image 340
yazanpro Avatar asked May 17 '26 06:05

yazanpro


1 Answers

If you want to use Linq, you can join the List<int> ids to the DataTable and since your list is already ordered, the results will be in that order:

var query =
    from l in ids
    join t in table.AsEnumerable() on l equals t.Field<String>(columnName)
    select t;

var orderedTable = query.CopyToDataTable();
like image 150
CodingYoshi Avatar answered May 18 '26 19:05

CodingYoshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!