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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With