How to use OrderBy in EntityFramework

c# entity-framework entity-framework-6 sql-order-by

Question

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)?

1
0
3/10/2017 11:56:59 AM

Accepted Answer

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

3
11/17/2016 10:19:43 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow