Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

want a Query to make order by variable in Linq query

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; 
like image 983
Azhar Avatar asked Jun 20 '10 07:06

Azhar


People also ask

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.

How do you order alphabetically in LINQ?

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.

How do I get data in descending order in LINQ?

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.

How do you write a query in LINQ?

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.


1 Answers

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.

like image 173
Kelsey Avatar answered Nov 15 '22 09:11

Kelsey