tags:

views:

378

answers:

4

I'm using SQL Server 2005 express I have a datetime field in a table witch contains date and time.

I want to select distinct the dates from the table ignoring the time part.

I used this code but the order by is ignored ! (the generated sql doesn't contain order by) :

        var dates = (from c in db.Comments
                     orderby c.Time descending
                     select c.Time.Day + "/" + c.Time.Month + "/" + c.Time.Year).Distinct();

Any ideas on how to do this are welcome.

Thanks

A: 

Try LinqPad, which lets you see the generated SQL. Play with different combinations.

Adam Ernst
+1  A: 

Try this:

var comments = from c in db.Comments
               select c.Time.Day + "/" + c.Time.Month + "/" + c.Time.Year).Distinct();

comments = comments.OrderBy(c => c.Time);
Lobut
+4  A: 

Use the Date property of the DateTime type.

var dates = from c in db.Comments
             group c by c.Time.Date into g
             orderby g.Key
             select g.Key;

or

var dates = (from c in db.Comments
            select c.Time.Date).Distinct().OrderBy(d => d);

An SQL expert can tell you which of these is better.

Jason
+2  A: 

order by is ignored!

Yes, you are instructing linq to order, and then to distinct. Distinct in linq is an operation that destroys ordering. You must orderby after the distinct:

query = query.Distinct().OrderBy(x => x);

Also, it is profane to use string manipulation to perform date logic. You should project using the Date property of DateTime.

David B