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);
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#.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With