在LINQ中将String转换为DateTime

use*_*153 9 c# linq

我有一个表格,格式如下.

PID     ID       Label        Value
------------------------------------------
1       1        First Name    Jenna
1       2        DOB           10/12/1980
Run Code Online (Sandbox Code Playgroud)

我需要检索所有PID,其中以J和DOB月份开头的名字是10.

在我的代码中,我在C#中的DataTable中检索这些,然后尝试使用LINQ来检索我想要的结果.这只是一个例子.这些标签可以是用户定义的任何内容.

使用LINQ我能够检索First Name以J开头的所有PID,但是每当我尝试为DOB Cast Cast时,我都会得到无效的错误.我无法更改数据库中的列类型,因为Value可以包含任何类型的信息.

这是我的一段代码.我是LINQ的新手,还在试图弄清楚它.

var resultQuery = from r in query.AsEnumerable()
where (r.Field<string>("Label") == Label  &&
r.Field<DateTime>("Value").Month == 10)
select r.Field<int>("PID");
Run Code Online (Sandbox Code Playgroud)

gor*_*ric 4

由于并非表的“值”列中的所有项目都可以转换为DateTime,因此您所拥有的内容将因无效转换而失败。您可以添加一个子句,该子句首先检查该值是否为 a DateTime,并且仅当它是时,才将其转换并检查.Month属性。

DateTime d;
var resultQuery = from r in query.AsEnumerable()
                  where (r.Field<string>("Label") == Label &&
                      DateTime.TryParse(r.Field<string>("Value"), out d) && 
                      d.Month == 10)
                  select r.Field<int>("PID");
Run Code Online (Sandbox Code Playgroud)

为了潜在地提高可读性,您还可以将其提取到一个单独的方法中:

var resultQuery = from r in query.AsEnumerable()
                  let d = TryGetDate(r.Field<string>("Value"))
                  where (r.Field<string>("Label") == Label &&
                      d != null && 
                      d.Month == 10)
                  select r.Field<int>("PID");

private DateTime? TryGetDate(string value)
{
    DateTime d;
    return DateTime.TryParse(value, out d) ? d : default(DateTime?);
}
Run Code Online (Sandbox Code Playgroud)

  • 为了可读性和“正确性”,我认为最好将日期逻辑放在单独的方法中(DateTime?TryGetDate(字符串值)),如果不可解析则返回 null ... (3认同)