Accepted answer

You may do any ordering. If column doesn't exist, just leave your input enumerable as it was before. To do this, create key selector that returns the same value for all elements.

See example:

using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;

static class Program
    public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression) where T : class
        Func<T, Int32> keySelector = (elem) =>
            PropertyInfo pi = typeof(T).GetProperty(sortExpression, typeof(Int32));
            if (pi == null)
                return 0; // return the same key for all elements

            return Int32.Parse(pi.GetValue(elem, null).ToString());

        return list.OrderBy(keySelector);

    static void Main(string[] args)
        // Create an array of strings to sort.
        string[] fruits = { "apricot", "orange", "banana", "mango", "apple", "grape", "strawberry" };

        // Sort by "column" Length
        foreach (string s in fruits.OrderBy<string>("Length"))

        // Sort by non-existing column
        foreach (string s in fruits.OrderBy<string>("ength"))

Related Articles