简体   繁体   中英

LINQ Queries with dynamic Order By - more than one field

I have a collection with name,date,category as parameters. I want to sort the list based on the input order of the three which changes dynamically. For ex: in one case i have to sort on the order date,name, category respectively. in another case the order is name, date and category.So i can have all the permutation and combinations. Can someone help me with a generic way to implement it.

LINQ already allows you to sort using multiple fields by adding the Queryable.ThenBy , QueryableThenByDescending , Enumerable.ThenBy or Enumerable.ThenByDescending functions after OrderBy.

Check Multiple “order by” in LINQ for a similar question and the discussion.

As an aside, you can convert an Enumerable to a Queryable simply calling AsQueryable on it, if you need a rare method that is not provided by Enumerable.

I also found here something that he might like: http://www.codeproject.com/Articles/27834/Generic-List-Sort-Function <-- hope it helps, it sorts by any input property. The property is taken through reflection.

Here is an example

// Just to get IOrderedEnumerable from the collection
// And set the default order
var orderedItems = context.Items.OrderBy(i => i.Name);

var orderByString = txtOrderBy.Text.ToLower();
switch(orderByString)
{
    case "category":
        orderedItems = orderedItems.OrderBy(i => i.Category);
        break;
    case "date":
        orderedItems = orderedItems.OrderBy(i => i.Date);
        break;
    default:
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM