Using LINQ And Converting DateTime To A String

The problem, I need the DateTime, but I really only need the date and I need to use it for something else.  Something that would like it to be a string.  How can I do this using LINQ?  Well it really isn’t all that hard.  If you try to use any of the .ToString or .To…. DateString you will get an error because it cannot do that in SQL.  Well don’t give up, you just need an extra step.

Basically you are going to get your data out of SQL before you try to convert that DateTime to a string.

First you do your normal LINQ query where you just get that DateTime, here is an example.

var vDates = (from d in oForm.tblSchedule
                      select new { scheduleDate = EntityFunctions.TruncateTime(d.dtSchedule) })
                      .Distinct();

Now here comes the fix.  Use something like the ToList() so that it iterates on it and is no longer in SQL.  Now you can use your .To…String methods.

var vDates = (from d in oForm.tblScheduleIn
                      select new { scheduleDate = EntityFunctions.TruncateTime(d.dtSchedule) })
                      .Distinct()
                      .ToList()
                      .Select(o => new {scheduleDate = o.scheduleDate.Value.ToShortDateString()});

Now I cannot claim credit for figuring this out on my own. I found an article about it on Stack Overflow.

Advertisements

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on October 22, 2012, in C#, LINQ and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: