OrderBy Column Name as String using Linq C# .Net Dynamic Sorting of Anonymous Types

If you’re familiar with Linq, you have undoubtedly used the popular “OrderBy” extension method. Unfortunately, this method does not accept a string value with the column name.

var data = from i in db.tablename
select i;

repeatername.datasource = data.OrderBy(i=>i.columnname); //this works

repeatername.datasource = data.OrderBy("columnname"); //this does not

To resolve, you can add the following small class or just the method to a generic DLL you use in your web application projects or create a new class or project for your extension methods.

Kudos to R. Prestol for help researching this one.

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

namespace YourAppName.Web
{
    public static class extensionmethods
    {
        public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
        {
            var param = Expression.Parameter(typeof(T), "p");
            var prop = Expression.Property(param, SortField);
            var exp = Expression.Lambda(prop, param);
            string method = Ascending ? "OrderBy" : "OrderByDescending";
            Type[] types = new Type[] { q.ElementType, exp.Body.Type };
            var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
            return q.Provider.CreateQuery<T>(mce);
        }
    }
}

Returning to our first code snippet, you can now do:

repeater.datasource = data.OrderByField("columnname");

Since this is an extension method, and exists in a class within the same namespace as your project or other referenced assembly, you can call the method directly from the IQueryable Linq data object without requiring any other inherits; this works similar to override functionality.

Read up about extension methods on MSDN or Google for other cool tricks you can do. Enjoy. 😉

References
Extension Methods (MSDN), http://msdn.microsoft.com/en-us/library/bb383977.aspx

Advertisements

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on May 24, 2011, in Programming & Development and tagged , , , , , , , , , , , . Bookmark the permalink. 7 Comments.

  1. This is absolutely great. Thank you so much.

  2. fantastic; I just couldn’t get the sidx+sord method to work when trying to sort jqGrid data, and this did the trick elegantly. Can’t believe it isn’t native in Linq

  3. That’s what I really looking for . thank you!

  4. fantastic – saved me hours of fruitless searcvhing

  5. Great!!! After two days You solved my problem!
    Thanx man!

  6. Great!!!! Thanks a lot man, great solution for a big problem!

  7. Thanks, only thing I needed to do to get it to work in LINQ pad was change:
    var prop = Expression.Property(param, SortField);
    To
    var fld = Expression.Field(param, SortField);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: