LINQ-To-SQL OrderBy with DateTime not working

I have this LINQ query. The date is stored as a string in the database, but I need to order it. So I convert it to DateTime, but it doesn't order.

   (from m in dbDataContext.TimeCards
    where m.TIMECARDDATE != ""
    && m.TIMECARDDATE != null
    orderby Convert.ToDateTime(m.TIMECARDDATE) descending
    select Convert.ToDateTime(m.TIMECARDDATE)).Distinct().ToList();

      

Any idea why this isn't working? I can't change the database, so I have to deal with the data the way it is. I am getting data back like this ...

 2/27/2009
 2/26/2009
 2/25/2009
 2/28/2009
 2/24/2009

      

+2


source to share


2 answers


Try evaluating the expression without sorting, and then apply sorting to the Distinct results:



(Linq-To-Sql-Expression).Distinct().OrderByDescending(x => x.TIMECARDDATE).ToList()

      

+7


source


First you can use string.IsNullOrEmpty()

instead of checking if the string is null or""

Also, it should work. You are probably reordering it outside of this code.



Note that this is not executed until you complete it (call GetEnumerator()

). Therefore, if you changed something before repeating it, that may be the reason.

ps TIMECARDDATE is it an object or a string?

+1


source







All Articles