Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Entities Distinct Clause

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
                 });
like image 572
Bob Avallone Avatar asked Feb 17 '11 21:02

Bob Avallone


2 Answers

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);
like image 103
Greg Avatar answered Sep 20 '22 13:09

Greg


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.

like image 23
Adam Rackis Avatar answered Sep 18 '22 13:09

Adam Rackis