我的数据从数据库中数据集
的形式到来。我然后将其设置为一个网格控件的数据源
之前做了的DataBind()
。我想了数据集
/ 数据表
排序上一列。该列到复杂的数据库进行排序,但我希望我可以排序像我将排序泛型列表即使用deligate。
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?
修改我不能得到任何这些答案为我工作,我想是因为我使用的 NET 2.0。
Edit I can't get any of these answer to work for me, I think because I am using .Net 2.0.
,你不能直接用委托的方式。一种解决方法是一个列的基础上所需要的序列添加到数据表重新presents的顺序,并设定(每行)的值。然后,您可以添加一个排序的看法这个新列。例如(使用LINQ做了排序,只是为了简单起见):
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++;
}
(如果你有一个类型化的数据集,那么我不认为你需要的演员一步,不然你就用你的类型化的DataRow子类)
(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)
在2.0(即没有LINQ等),你可以使用名单,其中,T&GT;
做的那种 - 多一点啰嗦,但是:
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++;
}
(同样,如果你使用的是类型化的数据集替代的DataRow)
(again, substitute DataRow if you are using a typed data-set)