5

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; 
Azhar
  • 19,214
  • 38
  • 134
  • 202

3 Answers3

6

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.

Kelsey
  • 45,595
  • 16
  • 119
  • 161
  • and what if I also have some join in the query?? – Azhar Jun 26 '10 at 07:19
  • @Azhar just add the `Join` after the `Where` and everything else should work just the same. The `Join` will just join to another `IQueryable`. – Kelsey Jun 26 '10 at 18:44
3
    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);
Kyaw Thurein
  • 2,366
  • 7
  • 33
  • 49
0

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.

Paul Turner
  • 35,361
  • 15
  • 90
  • 155
  • yes but in this I have to write multiple if statements?? can I declare orderedData out from if statement – Azhar Jun 20 '10 at 07:25