Custom MVC WebGrid Demo 1 · Server Code

using System;
using System.Linq;
using System.Linq.Expressions;

namespace MyMvc4App
    public static class ExtensionMethods
        // Need to create an extension method for ordering in both directions.
        // Standard Query Operators Overview:
        // Extension Methods:
        // How to: Implement and Call a Custom Extension Method:
        // This new extension method will call existing extension methods OrderBy and OrderByDescending, based on the string parameter sortDir.
        // These existing extension methods sorts elements in data structures that implement IQueryable<T>.
        // Queryable Class:
        // Queryable.OrderBy Method:
        // Queryable.OrderByDescending Method:
        // These existing extension methods accept an Expression<Func<TSource, TKey>> parameter.
        // Expression<TDelegate> represents TDelegate as a data structure in the form of an expression tree.
        // Expression<TDelegate> Class:
        // Expression Trees:
        // How to: Use Expression Trees to Build Dynamic Queries:
        // Func<TSource, TKey> is the delegate (the TDelegate in Expression<TDelegate> in this case).
        // Func<T, TResult> Delegate:
        // These existing methods return IOrderedQueryable<TSource> whose elements are sorted according to a key
        // IOrderedQueryable Interface:
        public static IOrderedQueryable<TSource> OrderByWithDirection<TSource, TKey>(
            this IQueryable<TSource> query, Expression<Func<TSource, TKey>> keySelector, string sortDir)
            if (sortDir.ToUpper().Equals("DESC"))
                return query.OrderByDescending(keySelector);
                return query.OrderBy(keySelector);