Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7626843
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T05:22:50+00:00 2026-05-31T05:22:50+00:00

I am writing a list sorting extension method. My input is the list and

  • 0

I am writing a list sorting extension method.
My input is the list and a string with property name and sort direction.
This string can have multiple properties like so:
“Name ASC, Date DESC” etc.

I already implemented the string parsing and used reflection to get the property itself from the string, but what I am stuck on now is how do I dynamically chain the orderby methods.

something like:
_list.orderBy(x=>x.prop1).thenBy(x=>x.prop2) etc.

Is there any way to build this dynamically?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T05:22:51+00:00Added an answer on May 31, 2026 at 5:22 am

    Use reflection to get from the string property names to a PropertyInfo’s. You can then build an expression tree using the PropertyInfo’s to dynamically construct all the orderbys. Once you have the expression tree, compile it to a delegate, (say Func, IEnumerable>) Pass in your _list parameter to this delegate and it will give you the ordered result as another enumerable.

    To get the reflection information for the generic method on Enumerable, have a look at the answer on this post:
    Get a generic method without using GetMethods

    public static class Helper
    {
        public static IEnumerable<T> BuildOrderBys<T>(
            this IEnumerable<T> source,
            params SortDescription[] properties)
        {
            if (properties == null || properties.Length == 0) return source;
    
            var typeOfT = typeof (T);
    
            Type t = typeOfT;
    
            IOrderedEnumerable<T> result = null;
            var thenBy = false;
    
            foreach (var item in properties
                .Select(prop => new {PropertyInfo = t.GetProperty(prop.PropertyName), prop.Direction}))
            {
                var oExpr = Expression.Parameter(typeOfT, "o");
                var propertyInfo = item.PropertyInfo;
                var propertyType = propertyInfo.PropertyType;
                var isAscending = item.Direction == ListSortDirection.Ascending;
    
                if (thenBy)
                {
                    var prevExpr = Expression.Parameter(typeof (IOrderedEnumerable<T>), "prevExpr");
                    var expr1 = Expression.Lambda<Func<IOrderedEnumerable<T>, IOrderedEnumerable<T>>>(
                        Expression.Call(
                            (isAscending ? thenByMethod : thenByDescendingMethod).MakeGenericMethod(typeOfT, propertyType),
                            prevExpr,
                            Expression.Lambda(
                                typeof (Func<,>).MakeGenericType(typeOfT, propertyType),
                                Expression.MakeMemberAccess(oExpr, propertyInfo),
                                oExpr)
                            ),
                        prevExpr)
                        .Compile();
    
                    result = expr1(result);
                }
                else
                {
                    var prevExpr = Expression.Parameter(typeof (IEnumerable<T>), "prevExpr");
                    var expr1 = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(
                        Expression.Call(
                            (isAscending ? orderByMethod : orderByDescendingMethod).MakeGenericMethod(typeOfT, propertyType),
                            prevExpr,
                            Expression.Lambda(
                                typeof (Func<,>).MakeGenericType(typeOfT, propertyType),
                                Expression.MakeMemberAccess(oExpr, propertyInfo),
                                oExpr)
                            ),
                        prevExpr)
                        .Compile();
    
                    result = expr1(source);
                    thenBy = true;
                }
            }
            return result;
        }
    
        private static MethodInfo orderByMethod =
            MethodOf(() => Enumerable.OrderBy(default(IEnumerable<object>), default(Func<object, object>)))
                .GetGenericMethodDefinition();
    
        private static MethodInfo orderByDescendingMethod =
            MethodOf(() => Enumerable.OrderByDescending(default(IEnumerable<object>), default(Func<object, object>)))
                .GetGenericMethodDefinition();
    
        private static MethodInfo thenByMethod =
            MethodOf(() => Enumerable.ThenBy(default(IOrderedEnumerable<object>), default(Func<object, object>)))
                .GetGenericMethodDefinition();
    
        private static MethodInfo thenByDescendingMethod =
            MethodOf(() => Enumerable.ThenByDescending(default(IOrderedEnumerable<object>), default(Func<object, object>)))
                .GetGenericMethodDefinition();
    
        public static MethodInfo MethodOf<T>(Expression<Func<T>> method)
        {
            MethodCallExpression mce = (MethodCallExpression) method.Body;
            MethodInfo mi = mce.Method;
            return mi;
        }
    }
    
    public static class Sample
    {
        private static void Main()
        {
          var data = new List<Customer>
            {
              new Customer {ID = 3, Name = "a"},
              new Customer {ID = 3, Name = "c"},
              new Customer {ID = 4},
              new Customer {ID = 3, Name = "b"},
              new Customer {ID = 2}
            };
    
          var result = data.BuildOrderBys(
            new SortDescription("ID", ListSortDirection.Ascending),
            new SortDescription("Name", ListSortDirection.Ascending)
            ).Dump();
        }
    }
    
    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    

    The result of the sample as shown in LinqPad

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing an application that displays a list of objects which the user can
Hi I am writing a linked list data type. I have an inner class
I have a UserControl with the following Property: public List<Rect> HotSpots { get {
I have a list of java beans, now I want to sort them with
I have a list of objects and I want to sort by passing the
I am over writing the product list in my extension but when I write
I'm writing an immutable linked list class in C, but one method is mysteriously
I'm writing a sortable list implementation in jQuery (b/c of the infamous scroll-in-div issue,
I'm writing a simple linked list based memory manager in the form: ...Header|Block|Header|Block... with
I am writing a web part against a list. The first thing I do

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.