如何在执行 DataBind 之前对 DataSet 进行排序?如何在、DataBind、DataSet

2023-09-06 05:36:13 作者:不过浮生一阙

I have data coming from the database in the form of a DataSet. I then set it as the DataSource of a grid control before doing a DataBind(). I want to sort the DataSet/DataTable on one column. The column is to complex to sort in the database but I was hoping I could sort it like I would sort a generic list i.e. using a deligate.

Is this possible or do I have to transfer it to a different data structure?

spark 中 RDD DataFrame Dataset区别

Edit I can't get any of these answer to work for me, I think because I am using .Net 2.0.

解决方案

Because of how DataTable (and DataView) sorting works, you can't use the delegate approach directly. One workaround is to add a column to the data-table that represents the order, and set the value (per row) based on the desired sequence. You can then add a Sort to the view on this new column. For example (using LINQ to do the sort, just for brevity):

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 data-set, then I don't think you need the Cast step, or you would use your typed DataRow subclass)

[edit to include 2.0]

In 2.0 (i.e. without LINQ etc) you could use a List<T> to do the sort - a bit more long-winded, 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, substitute DataRow if you are using a typed data-set)