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

Advertisement

About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on May 24, 2011, in Programming & Development and tagged , , , , , , , , , , , . Bookmark the permalink. 14 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. Great! thanks a lot , works great on our system.

  8. Fantastic! after three days of searching finally I found the answer, thanks you so much!

  9. Thanks a lot! Exactly what I needed

  10. Thank you! you saved my hours 😉

  11. 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);

  12. Hi,

    How do I do it with multiple columns?

    Thanks,
    Chen

  13. Amazing!!! Thanks for sharing.

  1. Pingback: Linq sorting with multiple column names in c# | BlogoSfera

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: