I have a table named Person
with two columns: (PersonId - key, PersonName
)
I'm trying to retrieve all persons ordered by PersonName
.
The following code does NOT order my result:
var persons = from p in MyContext.Persons.OrderBy(x=>x.PersonName) select p;
var res = persons.Distnct().ToArray();
Is it possible to perform the order in that stage (I know that moving the OrderBy
to the second row - after the evaluation - do the order)?
Linq documentation says:
The Distinct(...) method returns an unordered sequence that contains no duplicate values.
So order is not guaranteed to stay the same.
If you need guaranteed ordering after .Distinct()
then your only option is to apply .OrderBy()
again.
Reference:
https://msdn.microsoft.com/en-us/library/bb348436(v=vs.110).aspx
You can include both order by and distinct in a single query. Its working fine for me:
var persons = MyContext.Persons.OrderBy(x => x.Name).Select(x => x.Name).Distinct();
If you want to convert it to an array then use ToArray() method.