gpt4 book ai didi

.net - 如何在 LINQ 语句中使用 DateTime.TryParseExact

转载 作者:行者123 更新时间:2023-12-02 21:31:28 25 4
gpt4 key购买 nike

给定以下源数据:

Dim inputs = {New With {.Name="Bob", .Date="201405030500"},
New With {.Name="Sally", .Date="201412302330"},
New With {.Name="Invalid", .Date="201430300000"}}

我编写了以下 LINQ 查询(目的是在 Select 之前添加 Where success 子句作为过滤器,但我已将其省略并已在结果中包含 success 以便进行调试):

Dim result1 = From i in inputs
Let newDate = New DateTime
Let success = DateTime.TryParseExact(i.Date, "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.AssumeLocal, newDate)
Select New With {
.Name = i.Name,
.Success = success,
.Date = newDate
}

但是,我得到以下结果,newDate 未由 TryParseExact 填充:

Results without a parsed Date

因此,我重构了查询,将 TryParseExact 提取到匿名方法中,以获得以下结果:

Dim parseDate = Function(d As String)
Dim parsedDate As DateTime
Return New Tuple(Of Boolean, Date)(DateTime.TryParseExact(d, "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.AssumeLocal, parsedDate), parsedDate)
End Function

Dim result2 = From i in inputs
Let parsedDate = parseDate(i.Date)
Select New With {
.Name = i.Name,
.Success = parsedDate.Item1,
.Date = parsedDate.Item2
}

...这正确地给出了我:

Results with a parsed Date

但是,我想找到一种完全在 LINQ 语句内完成此操作的方法,而不需要使用匿名方法来创建元组。当然,我有一些可行的东西,但我想将其作为学术兴趣点。

我怀疑这可能是可能的,但我的问题是:

为什么result1查询没有使用解析的日期正确设置newDate

(我考虑过惰性求值,但我认为它不适用于此处。)

更新:

  • 谢谢Hamlet向我展示您实际上可以同时声明和调用匿名方法!头脑=爆炸!
  • 谢谢Jim建议使用 Nullable 而不是 Tuple!很有道理。
  • 谢谢Ahmad对于建议关闭,这对我来说肯定比匿名方法更干净。

由于下面的答案,我按如下方式重构了 LINQ(包括 Where 子句过滤器):

Dim result3 = From i in inputs
Let parsedDate = Function(d)
Dim dtParsed As DateTime
Return If(DateTime.TryParseExact(d, "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.AssumeLocal, dtParsed), dtParsed, New DateTime?)
End Function(i.Date)
Where parsedDate.HasValue
Select New With {
.Name = i.Name,
.Date = parsedDate.Value
}

Results with a parsed Date

这实现了我正在寻找的目标,并且我相信编译器能够优化生成的代码,但我仍然想确切地了解为什么 result1 没有工作。也许这是埃里克·利珀特或约翰·斯基特的问题。

最佳答案

我建议您使用TryParsers该库是专门为在 LINQ 查询中使用 TryParse 方法而创建的。

Dim query = From i In inputs
Let d = TryParsers.TryParse.DateTimeExact(i.Date, "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.AssumeLocal)
Select New With {
.Name = i.Name,
.Success = Not d Is Nothing,
.Date = d.Value
}

您不能使用范围变量 (let) 作为 ref/out 参数,因为 let 关键字创建一个只读变量(实际上它编译匿名对象的属性)。

关于.net - 如何在 LINQ 语句中使用 DateTime.TryParseExact,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22209328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com