.net 对数据表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12472913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a Data Table
提问by pasanmaduranga
I tried to sort a data table with following two ways
我尝试使用以下两种方式对数据表进行排序
table.DefaultView.Sort = "Town ASC, Cutomer ASC"
table.Select("", "Town ASC, Cutomer ASC")
But none of them wasn't worked. It always displays data in original order. Do you have any idea to solve the problem.
但他们都没有工作。它始终按原始顺序显示数据。你有什么想法来解决这个问题。
回答by Kapil Khandelwal
Try this:
尝试这个:
Dim dataView As New DataView(table)
dataView.Sort = " AutoID DESC, Name DESC"
Dim dataTable AS DataTable = dataView.ToTable()
回答by djalonsoc
This was the shortest way I could find to sort a DataTable without having to create any new variables.
这是我能找到的对 DataTable 进行排序而无需创建任何新变量的最短方法。
DataTable.DefaultView.Sort = "ColumnName ASC"
DataTable = DataTable.DefaultView.ToTable
Where:
在哪里:
ASC - Ascending
ASC - 升序
DESC - Descending
DESC - 降序
ColumnName - The column you want to sort by
ColumnName - 要排序的列
DataTable - The table you want to sort
DataTable - 要排序的表
回答by Steve
After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC") you should loop over the table using the DefaultView not the DataTable instance itself
在 DefaultView ( table.DefaultView.Sort = "Town ASC, Cutomer ASC")上设置排序表达式后,您应该使用 DefaultView 而不是 DataTable 实例本身循环遍历表
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable
而是使用 DataTable 的 Select 方法,生成一个 DataRow 数组。此数组按您的请求排序,而不是 DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
回答by Anant Dabhi
private void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;
DataRow[] foundRows = dt.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray = arr;
newDT.Rows.Add(data_row);
}
//clear the incoming dt
dt.Rows.Clear();
for (int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = newDT.Rows[i][j];
}
DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}
}
回答by Chris Sim
This worked for me:
这对我有用:
dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();

