ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

OrderBy(string sortExpression)

Orders a list based on a sortexpression. Useful in object databinding scenarios where the objectdatasource generates a dynamic sortexpression (example: "Name desc") that specifies the property of the object sort on.

Source

public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression)
{
    sortExpression += "";
    string[] parts = sortExpression.Split(' ');
    bool descending = false;
    string property = "";

    if (parts.Length > 0 && parts[0] != "")
    {
        property = parts[0];

        if (parts.Length > 1)
        {
            descending = parts[1].ToLower().Contains("esc");
        }

        PropertyInfo prop = typeof(T).GetProperty(property);

        if (prop == null)
        {
            throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'");
        }

        if (descending)
            return list.OrderByDescending(x => prop.GetValue(x, null));
        else
            return list.OrderBy(x => prop.GetValue(x, null));
    }

    return list;
}

Example

class Customer
{
  public string Name{get;set;}
}

var list = new List<Customer>();

list.OrderBy("Name desc");

Author: C.F.Meijers

Submitted on: 25 apr. 2008

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 28610