简体   繁体   English

如何在VB .net中对数据集进行排序

[英]How to sort dataset in VB .net

I am working on a code, where i need to sort the data received in dataset through database by date (which later is exported in the excel sheet and data should be sorted in the excel sheet by date).我正在处理一个代码,我需要按日期对通过数据库接收到的数据进行排序(稍后将其导出到 excel 表中,数据应按日期在 excel 表中排序)。

Following is the code snippet i used to sort.以下是我用来排序的代码片段。

Dim ds As DataSet
Dim dte As DataTable = ds.Tables(0).DefaultView.ToTable()
       dte.DefaultView.Sort = "DATE_START ASC" // Using this to sort
       dte.DefaultView.ToTable()

dte.DefaultView.Sort = "DATE_DUE ASC" is returning the true value, but still dte returns unsorted data. dte.DefaultView.Sort = "DATE_DUE ASC" 返回真实值,但 dte 仍然返回未排序的数据。 Not sure whats wrong here.不知道这里出了什么问题。 Is there any alternate approach to sort the data by date?有没有其他方法可以按日期对数据进行排序?

试试这个 ORDER BY

dte.DefaultView.Sort = "ORDER BY DATE_START ASC" 

您可以使用 DataTable.Select ( 文档)在过滤器表达式中不传递任何内容,在排序中您的列,然后对结果调用 CopyToDataTable ( 文档):

Dim dte = ds.Tables(0).Select("", "DATE_START ASC").CopyToDataTable()

You are already sorting the data correctly, so you must just be accessing it incorrectly.您已经正确地对数据进行了排序,因此您一定只是错误地访问了它。

'Don't create a DataSet that you don't need.
'If all you need is a DataTable, create a DataTable.
Dim table As New DataTable

'Configure and populate table here.

'Sort the associated view.
table.DefaultView.Sort = "DATE_START"

'This will display the data unsorted, because the DataTable itself is not sorted.
For Each row As DataRow in table.Rows
    Console.WriteLine($"{row("ID")}, {row("DATE_START"}")
Next

'This will display the data sorted.
For Each view As DataRowView in table.DefaultView
    Console.WriteLine($"{view("ID")}, {view("DATE_START"}")
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM