Our Code
  • Andreas Finne (gravatar)

    I found some really nice code the other day. Unfortunately I cannot say that I wrote it myself, but I think it’s so cool that it needs to be published here. It was written by “mazzy maxim” as Community Content to MSDN. What it does is to extend the OrderBy method for IEnumerables. You provide the name of the property to sort by, and the sort order.

    Without further ado, here is the code:

    public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string property, bool ascending)
    {
        var MyObject = Expression.Parameter(typeof(T), "MyObject");
        var MyEnumeratedObject = Expression.Parameter(typeof(IEnumerable<T>), "MyEnumeratedObject");
        var MyProperty = Expression.Property(MyObject, property);
        var MyLambda = Expression.Lambda(MyProperty, MyObject);
        var MyMethod = Expression.Call(typeof(Enumerable),
                                       ascending ? "OrderBy" : "OrderByDescending",
                                       new[] { typeof(T), MyLambda.Body.Type },
                                       MyEnumeratedObject,
                                       MyLambda);
        var MySortedLambda = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(MyMethod, MyEnumeratedObject).Compile();
        return MySortedLambda(items);
    }

    So what we have is a generic extension method for IEnumerables that creates a  lambda expression on the fly to sort the objects by the property with the given name.

    Pretty cool or what?

    Now, some of you may argue that sorting by the name of the property introduces magic strings and doesn’t feel “right”. I can agree with that to some extent, but it is not much different to NotifyPropertyChanged(“property”), and my opinion is that this extension method still can have its place.

    I have used it when I needed the sorting of an object collection to be in the ViewModel rather than in the View. The reason for this was that the collection could be changed by a synchronization thread, and since the sort order was stored in the View, the ordering got reset. By using this method in the ViewModel, the sorting state was moved away from the View. The object collection was shown in a table, and the property to sort by was chosen by clicking on a column header. Clicking the header changed the OrderedBy property exposed by the ViewModel, and the collection was re-sorted accordingly.

  • Leave a reply

    Name (required)
    Website