LINQ OrderBy query not working

_db.InstellingAdressens .Where(l => l.GEMEENTE.Contains(gem_query)) .OrderBy(q => q.GEMEENTE) .Select(q => q.GEMEENTE) .Distinct(); 

This is a request. it returns a List<string> , but the rows are not ordered at all. Why does OrderBy have no effect? and how to fix it?

+4
source share
4 answers

Try putting OrderBy at the end of your call.

 _db.InstellingAdressens. Where(l => l.GEMEENTE.Contains(gem_query)). Select(q=>q.GEMEENTE).Distinct(). OrderBy(q=>q).ToList(); 
+9
source

Distinct does not know that you ordered your items before they were received, so he cannot use this knowledge. Thus, he must assume that the elements are disordered and thus simply do what they want with them.

A typical implementation will use a hash table that is not ordered by what you usually want the elements to be ordered, so the result of a single operation is unordered.

As others have suggested, reorder your calls to make the order last, and you should get what you want.

+6
source

Change the order of calls

 _db.InstellingAdressens.Where(l => l.GEMEENTE.Contains(gem_query)).Select(q=>q.GEMEENTE).Distinct().OrderBy(q=>q.GEMEENTE).ToList(); 
+1
source

Try just putting orderby in the last request

 _db.InstellingAdressens .Where(l => l.GEMEENTE.Contains(gem_query)) .Select(q=>q.GEMEENTE) .Distinct() .OrderBy(q=>q.GEMEENTE).ToList(); 
+1
source

All Articles