vb.net DataTable.Select 将字符串值转换为日期格式并对其进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13771147/
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
DataTable.Select with converting string value to Date format and sort it
提问by George
I have a data table that is being returned by a 3rd party component, so I have no way of changing the SQL string to get what I want. So, I get a table with several columns, all of them are Strings. One of the columns is BILLDATEwhich is of type string, but actually holds a date in a MM/DD/YYYYformat.
我有一个由 3rd 方组件返回的数据表,所以我无法更改 SQL 字符串以获得我想要的。所以,我得到一个有几列的表,它们都是字符串。其中一列是BILLDATE,它是字符串类型,但实际上以MM/DD/YYYY格式保存日期。
Issue: I need to sort the records in descending order and pick the record with the biggest date.
问题:我需要按降序对记录进行排序并选择日期最大的记录。
CODE:
代码:
Dim dataRows As DataRow()
Dim dt As New DataTable
dt = GetTable()
dataRows = dt.Select("", "BILLDATE DESC")
Sample data:
样本数据:
10/23/2010
9/23/2010
8/23/2010
7/23/2010
6/23/2010
From the sample data, the 9/23/2010record is returned as the first record, not the 10/23/2010.
Here is what I tried:
从示例数据中,9/23/2010记录作为第一条记录返回,而不是10/23/2010. 这是我尝试过的:
dataRows = dt.Select("MAX(CONVERT(DateTime,BILLDATE))", "")- run-time Error
dataRows = dt.Select("MAX(CONVERT(DateTime,BILLDATE))", "")- 运行时错误
dataRows = dt.Select("", "Convert(BILLDATE,'System.DateTime')")- run-time Error
dataRows = dt.Select("", "Convert(BILLDATE,'System.DateTime')")- 运行时错误
I would prefer not to iterate through all the records to get the latest date and select it. Any ideas?
我不想遍历所有记录来获取最新日期并选择它。有任何想法吗?
EDIT 1 - 2012-12-07 4:42pm:
Added definition for dataRows. It is of type DataRow()
编辑 1 - 2012-12-07 4:42pm:添加了 dataRows 的定义。它是类型DataRow()
回答by Tim Schmelter
You can use DateTime.ParseExactwith multiple format strings. You need them since your "dates" sometimes have one and sometimes have two places. I would use Linq instead:
您可以使用DateTime.ParseExact多个格式字符串。您需要它们,因为您的“约会对象”有时有一个位置,有时有两个位置。我会改用 Linq:
Dim ordered = From row In dt.AsEnumerable()
Let billDate = Date.ParseExact(
row.Field(Of String)("Billdate"),
{"MM/dd/yyyy", "M/dd/yyyy"},
Globalization.CultureInfo.InvariantCulture,
Globalization.DateTimeStyles.None)
Order By billDate Descending
Select row
' if you want to create a new DataTable from the rows: '
Dim tblOrdered = ordered.CopyToDatatable()
回答by ForHelp
Dim LastDate As Date = dt.AsEnumerable().Max(Function(a) Convert.ToDateTime(a("BILLDATE")))

