Seration
Seration

Reputation: 233

Linq Order by alphabetical

I got a product table and want to get datas sort by alphabetical. But when i write this query they are still coming by id. I check a lot of page in google but cant find any source.

var product = Db.tablename
                .Where(s => s.colum == DropDownList2.SelectedValue)
                .OrderBy(s=> s.Name);

Upvotes: 18

Views: 42937

Answers (2)

Christos
Christos

Reputation: 53958

This query

var product = Db.tablename
                .Where(s => s.colum == DropDownList2.SelectedValue)
                .OrderBy(s=> s.Name);

will not be executed until it is asked to. So you have to change it to the following one:

var product = Db.tablename
                .Where(s => s.colum == DropDownList2.SelectedValue)
                .OrderBy(s=> s.Name).ToList();

The reason why that happens is that actually you just have declared a query. I mean you haven't executed it. That's the nature of LINQ queries, which in technical terms is called deffered execution. On the other hand if you call the ToList() method at the end of your query, you will trigger the immediate execution of this query and it's result will be a List of the same type with s.Name.

Upvotes: 25

Fals
Fals

Reputation: 6839

You must use ToList to execute the sort.

var product = Db.tablename
                .Where(s => s.colum == DropDownList2.SelectedValue)
                .OrderBy(s=> s.Name).ToList();

The order by does nothing, just executes the query, the ToList will do the sort for the original query.

Upvotes: 3

Related Questions