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?
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
Somethingclass more appropriate would be:Now if you pass in
nullforsortthe sorting will revert to the default sort order byAddedDate.