Stefanvds
Stefanvds

Reputation: 5916

LINQ query OrderBy doesn't work

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

this is the query. it returns a List<string> but the strings are not ordered at all. Why does the OrderBy have no effect? and how to fix it?

Upvotes: 4

Views: 4162

Answers (4)

Pranay Rana
Pranay Rana

Reputation: 176886

Try this just put orderby last of the query

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

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391286

Distinct has no knowledge that you have ordered your items before it gets them, so it can't use that knowledge. As such, it has to assume the items are unordered, and will thus just do what it wants with them.

A typical implementation will use a hashtable, which isn't ordered by what you normally want the items to be ordered by, so the result from the distinct operation is an unordered set.

So as others have suggested, change the ordering of your calls to do the ordering last, and you should get what you want.

Upvotes: 6

RaYell
RaYell

Reputation: 70414

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();

Upvotes: 9

Branimir
Branimir

Reputation: 4367

Change the order of calls

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

Upvotes: 1

Related Questions