2

I have a C# MVC project. I want to build statement in client app controller method to fetch JSON from web.api, for paging/sort in the view template. Can the sort order be passed to this code as a variable?

var container = new CourseService.Container(uri);
var query = container.Courses.OrderByDescending(c => c.Name).Skip(skip).Take(take).ToList();
Mark Hurd
  • 10,175
  • 10
  • 62
  • 96
Steve
  • 617
  • 8
  • 25
  • No you can't, you need to do something like this: [http://stackoverflow.com/questions/3078465/want-a-query-to-make-order-by-variable-in-linq-query][1] [1]: http://stackoverflow.com/questions/3078465/want-a-query-to-make-order-by-variable-in-linq-query – Chris L Mar 28 '14 at 09:21
  • Thanks Chris. Thought so...but wanted to check – Steve Mar 28 '14 at 09:29

1 Answers1

1

Why not add your own IEnumerable extension to do this?

public enum SortOrder
{
    Ascending,
    Descending
}

public static class EnumerableExtensions
{
    public static IEnumerable<T> OrderBy<T, TKey>(this IEnumerable<T> input,
        Func<T, TKey> keySelector, SortOrder order)
    {
        switch(order)
        {
            case SortOrder.Descending:
                return input.OrderByDescending(keySelector);
            default:
                return input.OrderBy(keySelector);
        }
    }
}

Then:

var output = container.Courses.OrderBy(c => c.Name, SortOrder.Descending);
Ant P
  • 23,644
  • 4
  • 62
  • 103
  • Ant Thanks for code. I'm a C# newbie. My controller method and variable parameter is in code below. How do I implement your code? public class HomeController : Controller { public ViewResult Index(string sortOrder) { – Steve Mar 30 '14 at 17:22
  • If you drop the `EnumerableExtensions` class and `SortOrder` enum somewhere into your codebase then you can just call it like I demonstrated above. If you want to use strings, you can adapt the method to take a string instead of a `SortOrder` but that's less robust as you lose the compile-time checking (i.e. you have to ensure that you get the string right every time). Better would be to change your controller action so that it looks like: `public ViewResult Index(SortOrder sortOrder)`. – Ant P Mar 30 '14 at 18:04