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.

1
2
3
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.

1
2
3
4
5
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.

Increment “sequence” column based on alphabetical order of another column

Assume the following schema:

text|sequence
----|--------
Foo |       1
Bar |       2
Baz |       3

How would I UPDATE the sequence column so it incremented starting at 1 with no gaps based on the alphabetical order of the text column?

The resulting data would look like:

text|sequence
----|--------
Foo |       3
Bar |       1
Baz |       2

 

Try this:

UPDATE A 
SET A.sequene = B.sequence 
FROM tableA A 
INNER JOIN (SELECT text, ROW_NUMBER() OVER (ORDER BY text) sequence 
            FROM tableA 
           ) AS B ON A.text = B.text