How to make order by Column variable because I have a dropdown on page and I want to show grid according to sord order selected in this Dropdown e.g Price, Code, rating, description etc etc. and I donot want to write a separate query for each column.
from lm in lDc.tbl_Products
where lm.TypeRef == pTypeId
orderby lm.Code ascending
select new;
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.
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 want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
There are the following two ways to write LINQ queries using the Standard Query operators, in other words Select, From, Where, Orderby, Join, Groupby and many more. Using lambda expressions. Using SQL like query expressions.
Assuming you want to do the sorting via SQL then you will need to pass in the sort column/type. The query is deferred until you actually do the select so you can build up the query in steps and once you are done execute it like so:
// Do you query first. This will NOT execute in SQL yet.
var query = lDC.tbl_Products.Where(p => p.TypeRef == pTypeId);
// Now add on the sort that you require... you could do ascending, descending,
// different cols etc..
switch (sortColumn)
{
case "Price":
query = query.OrderBy(q => q.Price);
break;
case "Code":
query = query.OrderBy(q => q.Code);
break;
// etc...
}
// Now execute the query to get a result
var result = query.ToList();
If you want to do it outside of SQL then just get a basic result with no sorting and then apply an OrderBy to the result base on the sort criteria you need.
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