Due to how the sorting of the DataTable (and DataView) works, you cannot use the delegate approach directly. One way is to add a column to the data table that represents the order, and set a value (for each row) based on the desired sequence. Then you can add sorting to the view in this new column. For example (using LINQ to sort, just for short):
var sorted = table.Rows.Cast<DataRow>().OrderBy(row => your code);
int sequence = 0;
foreach(var row in sorted)
{
row["sequence"] = sequence++;
}
(if you have a typed dataset, then I don’t think you need the Cast step, or you will use your own typed subclass of DataRow)
[edit to include 2.0]
In 2.0 (i.e. without LINQ, etc.) you can use List<T>to perform sorting - a little longer, but:
List<DataRow> sorted = new List<DataRow>();
foreach(DataRow row in table.Rows)
{
sorted.Add(row);
}
sorted.Sort(delegate(DataRow x, DataRow y) { your code });
int sequence = 0;
foreach(DataRow row in sorted)
{
row["sequence"] = sequence++;
}
(again, replace DataRow if you are using a typed dataset)
source
share