Want a query to execute a variable order in a Linq query

How to make an order for the Column variable, because I have a drop-down list on the page, and I want to show the grid in accordance with the sord order selected in this drop-down list, for example Price, Code, rating, description, etc. etc., and I do not 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; 
+5
source share
3 answers

Assuming you want to sort through SQL, you will need to go through the sort / type column. The request is postponed until you actually make a choice so that you can create the request step by step, and as soon as you finish execution like this:

// 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();

SQL, , OrderBy , .

+6
    public static IEnumerable<T> OrderByIf<T,TKey>(this IEnumerable<T> source, bool condition, Func<T, TKey> keySelector)
    {
        return (condition) ? source.OrderBy(keySelector).AsEnumerable() : source;
    }

:

            var query = lDC.tbl_Products.Where(p => p.TypeRef == pTypeId)
                                    .OrderByIf(sortColumn == "Price", p => p.Price)
                                    .OrderByIf(sortColumn == "Code", p => p.Code);
+3

"" LINQ .

, . , .

var data = from lm in lDc.tbl_Products
           where lm.TypeRef == pTypeId
           select new;

, , .

var orderedData = from lm in data
                  order lm.Code ascending
                  select new;

// TODO: Display orderedData in a grid.

, , , . , , "" .

0

All Articles