[英]How can I convert a DateTime variable in a LINQ expression?
Given this expression:给定这个表达式:
var q = (from c in db.ContattiTitoliStudio
where ...
orderby c.Data descending
select new
{
c.ID,
Date = c.Data.ToString("MM dd, YYYY"),
});
c.Data is nullable
, but also with a non-nullable var is the same: " ...No overload for method 'ToString' takes 1 arguments...
" c.Data is nullable
的,但也与不可空的 var 相同:“ ...No overload for method 'ToString' takes 1 arguments...
”
I tried nullable
, not nullable, with (c.Data.=null)...
, with String.Format
, with DateTime.Parse
, etc... But I can't format c.Date
the way I want.我用
(c.Data.=null)...
、 String.Format
、 DateTime.Parse
等尝试了nullable
, not nullable ,但我无法按照我想要的方式格式化c.Date
。
In SQL Server I use datetime
as the type.在 SQL 服务器中,我使用
datetime
作为类型。
If I use normal Date = c.Date
this will be displayed as "01/01/2011 0.0.00".如果我使用正常的
Date = c.Date
这将显示为“01/01/2011 0.0.00”。
Make use of Nullable(ie?? operator) Operation which is exists in C#利用 C# 中存在的Nullable(ie?? operator)操作
var q = (from c in db.ContattiTitoliStudio
where ...
orderby c.Data descending
select new
{
c.ID,
Date = (c.Data ?? DateTime.MinValue).ToString("MM dd, YYYY"),
});
Note: DateTime.MinValue is used when the value of c.Data is null which used to avoid null注意:当 c.Data 的值为 null 时使用 DateTime.MinValue ,以避免 null
Have you tried this?你试过这个吗?
Date = c.Data.HasValue ? c.Data.Value.ToString("MM dd, YYYY") : string.Empty
Ok,finally this is the solution:好的,最后这是解决方案:
var test= from e in db.Employees.ToList() select new {Time= e.Date.ToString()};
from msdn forums:来自 msdn 论坛:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/208396f4-0406-41c6-b55f-0d8bb5d14b2c http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/208396f4-0406-41c6-b55f-0d8bb5d14b2c
You didn't tell us, but I'm guessing that ContattiTitoliStudio.Data
is Nullable<DateTime>
.你没有告诉我们,但我猜
ContattiTitoliStudio.Data
是Nullable<DateTime>
。 In this case, you should say在这种情况下,你应该说
Date = c.Data.HasValue ? "null" : c.Data.Value.ToString("MM dd, YYYY")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.