Page 1 of 1

Distinct List of ShortDates from Linq Query?

Posted: Mon 13 Feb 2012 15:10
by s1buick
I need to fill a dropdown with a distinct list of ShortDates from a Linq query to an Oracle table but I haven't quite got it. Here's what I have come up with so far:


This first part gives me a list of distinct DateTimes down to the minute and second which is more detail than I want.

Code: Select all

var dates = (from those in db.RTPCR_CNDATs
                select those.UPLOADDATE).Distinct().OrderByDescending(d => d.Value).AsQueryable();

Returns:
...
{1/24/2012 12:54:15 PM}
{1/24/2012 12:54:14 PM}
{1/18/2012 3:50:56 PM}
{1/18/2012 3:50:55 PM}
... etc.


Then this second part gives me a list of short dates but they are not distinct and I'm not finding where and how to get that distinct list.

Code: Select all

var dateResults = from d in dates.ToList()
                    select new { d.Value }.Value.ToShortDateString();

Returns:
...
"1/24/2012"
"1/24/2012"
"1/18/2012"
"1/18/2012"
... etc.

Could someone please help a nube with the correct syntax for what seems like it should be a fairly common need?

Thanks!

Posted: Tue 14 Feb 2012 11:42
by MariiaI
The Distinct() method should be applied to short dates, i.e., after the ToShortDateString() method is invoked.
So, you can try do the second part this way:

Code: Select all

var dateResults = (from d in dates.ToList()
                   select new { d.Value }.Value.ToShortDateString()).Distinct();
JIC: the 'select new { d.Value }' construction is not safe; if one of objects in the list is null, it will cause an exception.

Posted: Tue 14 Feb 2012 16:02
by s1buick
Beautiful! Thank You!

In this case the UPLOADDATE field can't be null but, for future reference, are you suggesting something like this to make it "safe?"

Code: Select all

var dateResults = (from d in dates.ToList() where d.Value != null
                            select new { d.Value }.Value.ToShortDateString()).Distinct();
Just trying to pick up as much as I can as I go along. :)

Thanks

Posted: Wed 15 Feb 2012 08:08
by MariiaI
Try using d.HasValue instead of d.Value. Because if the object is null, d.Value will throw exception: System.InvalidOperationException.

Code: Select all

var dateResults = (from d in dates.ToList() where d.HasValue
                            select new {d.Value}.Value.ToShortDateString()).Distinct();
For more information, see http://msdn.microsoft.com/en-us/library/1t3y8s4s

JIC: As far as I can understand, this question does not apply to our products. Please use this forum for questions about LinqConnect only.

Posted: Thu 16 Feb 2012 14:49
by s1buick
Understood. Thank you for taking the time to help me out this time. Your answers have pointed me in the right direction and your time is greatly appreciated!

Thank you