开发者

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 descendi开发者_StackOverflow社区ng
                     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..."

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.

In SQL Server I use datetime as the type.

If I use normal Date = c.Date this will be displayed as "01/01/2011 0.0.00".


Have you tried this?

Date = c.Data.HasValue ? c.Data.Value.ToString("MM dd, YYYY") : string.Empty


Make use of Nullable(i.e ?? operator) Operation which is exists in C#

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


Ok,finally this is the solution:

var test= from e in db.Employees.ToList() select new {Time= e.Date.ToString()};

from msdn forums:

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>. In this case, you should say

Date = c.Data.HasValue ? "null" : c.Data.Value.ToString("MM dd, YYYY")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜