Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Distinct values with LINQ [duplicate]

Tags:

c#

sorting

linq

Possible Duplicate:
How do I get a distinct, ordered list of names from a DataTable using LINQ?

This is my first question here. I am getting a list of distinct values for a drop-down list from my database like so:

var plocQ = (from m in db.SERVICE_NRS
             orderby m.PLOC
             select new { PlocID = m.PLOC, value = m.PLOC }).Distinct();

The ordering seems to have no effect, I have to do this:

var plocQ = (from m in db.SERVICE_NRS
             select new { PlocID = m.PLOC, value = m.PLOC }).Distinct();

plocQ = from s in plocQ
        orderby s.PlocID
        select s;

I am wondering if this has something to do with LINQ or the database? I am a bit new to LINQ and have written too much SQL before. Any ideas?

like image 379
CyMark Avatar asked Aug 05 '11 21:08

CyMark


People also ask

How to get Distinct values in LINQ c#?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

Does distinct maintain order?

Java Stream distinct() MethodIf the stream is ordered, the encounter order is preserved. It means that the element occurring first will be present in the distinct elements stream.

Is LINQ orderby stable?

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.

How LINQ Distinct works?

LINQ Distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax. LINQ Distinct is an operator which comes under Set Operator.


1 Answers

It's because you're changing what's in your projection after you sort the initial results. Distinct doesn't guarantee that the order is preserved.

Incidentally, even if it did work that way, you still wouldn't want to! You'd be sorting through the whole list of items, even though some of them were just going to be thrown out.

If you just want to do this all in one statement, you can do this:

var plocQ = (from m in db.SERVICE_NRS
             select new { PlocID = m.PLOC, value = m.PLOC })
            .Distinct()
            .OrderBy(s => s.PlocID);
like image 143
Justin Morgan Avatar answered Oct 23 '22 02:10

Justin Morgan