2

I am writing a function with a signature like this where I am sorting the model data among other things:

public MyModel GetModel(IQueryable<Something> query, string sort, 
   int page, int PageSize)
{
   ...
   viewModel.Something = query.OrderByDescending(o => sort)
          .Skip((page - 1) * pageSize).Take(pageSize).ToList();
   ...
}

Problem is I want to pass in a default sort parameter which is what I want to sort against if the parameter "sort" is null or empty. For example, this might be:

.OrderByDescending(o => o.AddedDate);

I have tried all sorts of things (for instance passing in a Func) to pass in something to this function to tell it to use AddedDate or whatever I choose to sort the records if sort is null but nothing works. How would I implement such a thing?

Eranga
  • 32,181
  • 5
  • 97
  • 96
Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • possible duplicate of [Dynamic LINQ OrderBy](http://stackoverflow.com/questions/41244/dynamic-linq-orderby) – Eranga Jan 25 '12 at 14:45

2 Answers2

3

Your current code doesn't make much sense - you are sorting by a single value, not a property of the items you want to sort - if you want to be able to sort by any string property within your Something class more appropriate would be:

public MyModel GetModel(IQueryable<Something> query, Func<Something, string> sort, 
   int page, int PageSize)
{
   Func<Something, string> actualSort = sort ?? (o => o.AddedDate);
   ...
   viewModel.Something = query.OrderByDescending(actualSort)
          .Skip((page - 1) * pageSize).Take(pageSize).ToList();
   ...
}

Now if you pass in null for sort the sorting will revert to the default sort order by AddedDate.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

Your best bet is to use Dynamic Linq. It allows you to pass the sort key as a string:

query.OrderByDescending(sort)...
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Copy the DynamicQuery.cs file from Visual Studio samples into your project, add a `using System.Linq.Dynamic;` in your code, and you're good to go ; you will see the new OrderBy overloads in intellisense – Thomas Levesque Jan 25 '12 at 15:09
  • I searched, I don't have DynamicQuery on my computer and even if I did, not sure how it would help. – Sachin Kainth Jan 25 '12 at 15:26
  • @Sachin, did you read the link I posted? It explains where you can download the samples, and where you can find the file in the samples. – Thomas Levesque Jan 25 '12 at 15:28