Sorting DataTable by custom list order
I am looking for a sort DataTable
based on a specific column and an existing sorted list. This is what I came up with:
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 there might be some other solution that works better.
+3
source to share
1 answer
If you want to use the Linq, you can join List<int> ids
in DataTable
, and because your list is already sorted, the results are in the following 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();
+1
source to share