want a Query to make order by variable in Linq que

2020-02-29 01:56发布

问题:

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; 

回答1:

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.



回答2:

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

Usage:

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


回答3:

You can "build up" a LINQ query in separate steps.

Generate your base query to return the information unsorted. This query will not be executed until you try and enumerate the results.

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

Then in your event handler, apply whatever sorting you wish before binding the results to the grid.

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

// TODO: Display orderedData in a grid.

The full query you enumerate over is the one which will be evaluated. This means you can run a separate query for each item in your drop down, built from a "base" query.