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?
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).
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.
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With