Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Order by alphabetical

Tags:

c#

asp.net

linq

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);
like image 970
Seration Avatar asked May 15 '14 21:05

Seration


People also ask

How do you order alphabetically in LINQ?

The idea is to use LINQ's OrderBy() method to create a sorted collection of all characters in the string, and then combine all characters together with the String. Concat() method. That's all about sorting characters of a string in alphabetical order in C#.

How do I use ascending order in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

What is the use of OrderBy in C#?

In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.


2 Answers

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.

like image 77
Christos Avatar answered Sep 27 '22 02:09

Christos


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.

like image 20
Fals Avatar answered Sep 23 '22 02:09

Fals