问题描述
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?
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)
这篇关于如何在执行 DataBind 之前对 DataSet 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!