13

I want to add a distinct to the code below. I cannot figure out the exact syntax. Thanks in advance.

var testdates = (from o in db.FMCSA_ME_TEST_DATA
                 orderby o.DATE   
                 select new
                 {
                    RequestDate = o.DATE
                 });
MiniRagnarok
  • 959
  • 11
  • 23
Bob Avallone
  • 979
  • 7
  • 20
  • 36

3 Answers3

20

Use the Distinct() extension method.

Note that Distinct() may negate the existing orderby (I've noticed this in LINQ to SQL), so you may want to use the OrderBy() method afterwards.

var testdates = (from o in db.FMCSA_ME_TEST_DATA
                 select new
                 {
                     RequestDate = o.DATE
                 }).Distinct().OrderBy(x => x.RequestDate);
Greg
  • 23,155
  • 11
  • 57
  • 79
  • Are you sure about Distinct() negating an order by? I'm not seeing that behavior (running a similar query), and would be very surprised if I did – Adam Rackis Feb 17 '11 at 22:00
  • @Adam - I have encountered the OrderBy/Distinct issue with LINQ to SQL, but it may not be a problem for other LINQ providers. See http://programminglinq.com/blogs/marcorusso/archive/2008/07/20/use-of-distinct-and-orderby-in-linq.aspx – Greg Feb 17 '11 at 22:02
  • Wow - didn't know about that bug. I hope that's fixed in EF4, regardless though it shouldn't affect *this* query. +1 for posting that though. – Adam Rackis Feb 17 '11 at 22:16
  • @Adam - Yeah, it's annoying - especially because IQueryable meant in theory that you could use the same queries against various providers. In practice, you have to be aware of bugs like this (or pull your hair out). – Greg Feb 17 '11 at 22:28
  • [Linq Operations Grouped By Effect on Order](http://stackoverflow.com/a/204777/39396) – Carl G Mar 03 '13 at 10:33
3
var testdates = (from o in db.FMCSA_ME_TEST_DATA
                 orderby o.DATE   
                 select new
                 {
                    RequestDate = o.DATE
                 }).Distinct();

The trick is to wrap your query in parenthesis so you can call the distinct method, which you already did, so all you needed was to tack on the method call at the end.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
1

Seems like this should work:

            var testdates = (
                        from o in db.FMCSA_ME_TEST_DATA
                        orderby o.DATE
                        select new { RequestDate = o.DATE }
                        ).Distinct();

Check this link: http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#distinct2