LINQ将字符串转换为日期时间

LINQ将字符串转换为日期时间,linq,string,datetime,Linq,String,Datetime,在SQL中,我是这样做的: DateMonth=convert(datetime, convert(char(6), AASI.Inv_Acctcur) + '01') 在林克怎么做?字符串的格式如下: "yyyyMMdd" 谢谢, 伊利 编辑: SQL使用示例: SELECT convert(datetime, '20161023', 112) -- yyyymmdd 可在此处找到:列出了LINQ to SQL不支持的所有转换方法 Convert.ToDateTime未在其中列出。因此

在SQL中,我是这样做的:

DateMonth=convert(datetime, convert(char(6), AASI.Inv_Acctcur) + '01')
在林克怎么做?字符串的格式如下:

"yyyyMMdd"
谢谢,
伊利

编辑:

SQL使用示例:

SELECT convert(datetime, '20161023', 112) -- yyyymmdd 
可在此处找到:

列出了
LINQ to SQL
不支持的所有转换方法


Convert.ToDateTime
未在其中列出。因此,我想您可以使用Convert.ToDateTime来做您想做的事情。

这不是LINQ或任何支持LINQ over Expression trees的提供程序(如LINQ to SQL、LINQ to Entities、LINQ to NHibernate、LLBLGen Pro等)的典型功能。这只是一个语言问题。您想知道如何将格式yyyyMMdd转换为
DateTime

诀窍是在LINQ(over Expression trees)查询中不进行转换,因为LINQ提供程序将无法对其进行转换,或者如果可以,您将获得非常特定于提供程序的实现

因此,诀窍是将其作为字符串从数据库中取出(当然更好:更改数据库模型),并将其转换为.NET中的
DateTime
。例如:

// Doing .ToArray is essential, to ensure that the 
// query is executed right away.
string[] inMemoryCollectionStrings = (
    from item in db.Items
    where some_condition
    select item.Inv_Acctcur).ToArray();

// This next query does the translation from string to DateTime.
IEnumerable<DateTime> dates =
    from value in inMemoryCollectionStrings
    select DateTime.ParseExact(value, "yyyyMMdd", 
        CultureInfo.InvariantCulture);

也许我没有领会你的意思,但是在Linq中,
datatime
列已经是
DateTime
,所以你可以只做
DateTime.Month
。如果
datetime
是数据库中的字符串,则可以使用
datetime d=datetime.Parse(datetime)
。但是这与Linq.AASI.Inv_Acctcur无关,它是一个6个字符的字符串,需要转换为datetime,所以我在这个字符串中添加了“01”。我尝试了DateTime.Parse(DateTime+“01”),但这不起作用。实际上是这个DateTime.Parse(“20101001”),但问题是我的字符串的格式是“yyyyMMdd”,所以如果我尝试转换.ToDateTime(“20101001”),这是不起作用的。我的问题是如何在一行中进行转换,我认为在你的例子中,最好先把所有的数据放到内存中,然后过滤结果。如果有大量数据,最好找到另一种方法。@onCeluMurturer:I认为这是由
inMemoryCollectionString
变量名:-)所暗示的
DateTime.ParseExact(value, "yyyyMMdd", CultureInfo.InvariantCulture);