C# 将字符串转换为LINQ中的日期时间值

C# 将字符串转换为LINQ中的日期时间值,c#,sql-server,linq-to-sql,C#,Sql Server,Linq To Sql,假设我有一个以字符串格式存储日期时间(yyyyMMdd)列表的表。 如何提取它们并将其转换为日期时间格式dd/MM/yyyy e、 g.20101->2012年1月1日 我尝试了以下方法: var query = from tb in db.tb1 select new { dtNew = DateTime.ParseExact(tb.dt, "dd/MM/yyyy", null); }; 但结果是,错误表明ParseExact函数无法重新格式化。可能值得在本地进行解析,而不是通过AsEnum

假设我有一个以字符串格式存储日期时间(yyyyMMdd)列表的表。 如何提取它们并将其转换为日期时间格式dd/MM/yyyy

e、 g.20101->2012年1月1日

我尝试了以下方法:

var query = from tb in db.tb1 select new { dtNew = DateTime.ParseExact(tb.dt, "dd/MM/yyyy", null); };

但结果是,错误表明ParseExact函数无法重新格式化。

可能值得在本地进行解析,而不是通过
AsEnumerable在数据库中进行解析:

var query = db.tb1.Select(tb => tb.dt)
                  .AsEnumerable() // Do the rest of the processing locally
                  .Select(x => DateTime.ParseExact(x, "yyyyMMdd",
                                                CultureInfo.InvariantCulture));
最初的选择是为了确保只获取相关列,而不是整个实体(仅针对大部分被丢弃的实体)。我还避免使用匿名类型,因为这里似乎没有任何意义

顺便说一下,请注意我是如何指定不变区域性的——您几乎肯定不想只使用当前区域性。我已经更改了用于解析的模式,因为听起来您的源数据是
yyyyMMdd
格式的


当然,如果可能的话,您应该更改数据库模式,将日期值存储在基于日期的列中,而不是作为文本。

如前所述,最好将日期存储为数据库中的日期类型列,但如果您只想将字符串从一种格式转换为另一种格式,您可以执行以下操作:

db.tb1.Select(x => String.Format("{0}/{1}/{2}", x.Substring(6, 2), x.Substring(4, 2), x.Substring(0, 4))

在SQL Server中创建一个UDF,然后导入到linq to SQL项目中,并在比较中使用

-- =============================================
-- Author:      
-- Create date: 
-- Description: Convert varchar to date
-- SELECT dbo.VarCharAsDate('11 May 2016 09:00')
-- =============================================
CREATE FUNCTION VarCharAsDate
(
    -- Add the parameters for the function here
    @DateAsVarchar NVarchar(100)
)
RETURNS DateTime
AS
BEGIN
    -- Declare the return variable here

    if IsDate(@DateAsVarchar) = 1 BEGIN
        -- Return the result of the function
        RETURN convert(datetime, @DateAsVarchar, 109)
    END
    RETURN NULL
END
GO
然后在代码中

.Where(p => ValueDateTime > db.VarCharAsDate(p.Value))

将列的数据类型更改为Datetime