DataTable.DefaultView.Sort不排序

时间:2009-07-30 18:45:39

标签: c# datatable sorting

我对DataTable.DefaultView.Sort感到困惑。这是我想要使用它的代码段。

actionLogDT.DefaultView.Sort = "StartDate";

foreach (CustomerService.ActionLogStartEndRow logRow in actionLogDT)
{
  // code here
}

我见过的样本不使用foreach循环,因此让我对如何处理这个问题感到困惑。它没有像我想象的那样排序。

我看到.DefaultView返回一个视图,而.Table给出了一个编译错误。

9 个答案:

答案 0 :(得分:28)

actionLogDT.DefaultView.Sort = "StartDate";

actionLogDT = actionLogDT.DefaultView.ToTable();

答案 1 :(得分:10)

对视图进行排序不会更改表中数据的排序顺序,只会更改视图中的顺序。如果您在视图上执行foreach,将DataRowView中的行转换回强类型行,它应该可以工作。

foreach (DataRowView logRowView in actionLogDT.DefaultView)
{
    CustomerService.ActionLogStartEndRow logRow = logRowView.Row as CustomerService.ActionLogStartEndRow;
    // code here
}

答案 2 :(得分:7)

我不得不采取略微不同的方法。 This post是我能找到的最接近我的代码的工具。以下是工作结果:

actionLogDT.DefaultView.Sort = "StartDate";
DataView dv = actionLogDT.DefaultView;

foreach (DataRowView logRow in dv) { . . . }

从那里我只需要将值转换回正确的类型。

(string)logRow["Status"].ToString()

答案 3 :(得分:3)

foreach (var logRow in actionLogDT.DefaultView.ToDataTable()) { ... }

答案 4 :(得分:3)

此外,由于您似乎想要遍历记录,因此您可以遍历dataRowView中的DefaultView个对象。

foreach (DataRowView drv in table.DefaultView)
{
    string strValue = drv["ColumnName"].ToString();
    // its also worth mentioning that a DataRowView has a Row
    strValue = drv.Row["ColumnName"].ToString();
}

答案 5 :(得分:1)

请试试这个:

actionLogDT.DefaultView.Sort = "["+actionLogDT.Columns[0].ColumnName+"] asc";

答案 6 :(得分:0)

好奇:你为什么使用 DataRowView

foreach (DataRow row in actionLogDT.Rows)
{
  Console.WriteLine(row["Status"]);
}

答案 7 :(得分:0)

如果您需要数据表,那么您可以执行以下操作:

var dv = actionLogDT.DefaultView;
dv.Sort = "StartDate";

actionLogDT = dv.ToTable();

答案 8 :(得分:0)

在 VB.NET 中,下面的代码是我调用解决方案的最佳方式。只需将您的 origtable 复制到 DataView,然后可以使用简单的 .sort 命令对数据视图进行排序,然后将新表设置为等于(原始表的)排序视图.之后使用排序表 dt 进行处理。

Dim View1 As DataView = New DataView(origtable)
View1.Sort = "LastName"
Dim dt As DataTable = View1.ToTable