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

  • SEARCH
  • Home
  • 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 9118755
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T05:13:50+00:00 2026-06-17T05:13:50+00:00

I am trying to build an expression for sorting, and i wrote code that

  • 0

I am trying to build an expression for sorting, and i wrote code that sorts my list using one property.

But I need to sort it firstly by one property, secondly by another property and so on.

I mean I want to build an expression that will implement something like that: students.OrderBy(fistExpression.Compile()).ThenBy(secondImpression.Complie()).ThenBy(thirdExpression.Compile()).

So how to dynamically put that ThenBy methods?

Here is my code:

Type studentType = typeof(Student);
ParameterExpression studentParam = Expression.Parameter(studentType, "x");
MemberInfo ageProperty = studentType.GetProperty("Age");
MemberExpression valueInNameProperty = 
     Expression.MakeMemberAccess(studentParam, ageProperty);
Expression<Func<Student, int>> orderByExpression =
     Expression<Func<Student, int>>.Lambda<Func<Student, int>>(valueInNameProperty, studentParam);
var sortedStudents = students.OrderBy(orderByExpression.Compile());
  • 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-06-17T05:13:51+00:00Added an answer on June 17, 2026 at 5:13 am

    My solution:

    public static Func<Student, object> BuildPredicate(string propertyName)
    {
        Type studentType = typeof(Student);
        ParameterExpression studentParam = Expression.Parameter(studentType, "x");
        MemberInfo ageProperty = studentType.GetProperty(propertyName);
        MemberExpression valueInNameProperty = Expression.MakeMemberAccess(studentParam, ageProperty);
        UnaryExpression expression = Expression.Convert(valueInNameProperty, typeof (object));
        Expression<Func<Student, object>> orderByExpression = Expression.Lambda<Func<Student, object>>(expression, studentParam);
        return orderByExpression.Compile();
    }
    

    in your expression making code is added casting to object.

    That is how you can create a chain of ThenBy:

    var sortedStudents = students.OrderBy(BuildPredicate("Age"));
    foreach (var property in typeof(Student).GetProperties().Where(x => !String.Equals(x.Name, "Age")))
    {
        sortedStudents = sortedStudents.ThenBy(BuildPredicate(property.Name));
    }
    
    var result = sortedStudents.ToList();
    

    Finally, Student sample class:

    public class Student
    {
        public int Age { get; set; }
        public string Name { get; set; } 
    }
    

    Update:

    Another approach is using attributes to mark properies from your Student to use them in OrderBy and ThenBy. Like:

    public class Student
    {
        [UseInOrderBy]
        public int Age { get; set; }
    
        [UseInOrderBy(Order = 1)]
        public string Name { get; set; } 
    }
    
    [AttributeUsage(AttributeTargets.Property)]
    internal class UseInOrderByAttribute : Attribute
    {
        public int Order { get; set; }
    }
    

    That is how you can build sorting chain using UseInOrderByAttribute:

    Type studentType = typeof (Student);
    var properties = studentType.GetProperties()
                                .Select(x => new { Property = x, OrderAttribute = x.GetCustomAttribute<UseInOrderByAttribute>() })
                                .Where(x => x.OrderAttribute != null)
                                .OrderBy(x => x.OrderAttribute.Order);
    
    var orderByProperty = properties.FirstOrDefault(x => x.OrderAttribute.Order == 0);
    if (orderByProperty  == null)
        throw new Exception("");
    
    var sortedStudents = students.OrderBy(BuildPredicate(orderByProperty.Property.Name));
    foreach (var property in properties.Where(x => x.Property.Name != orderByProperty.Property.Name))
    {
        sortedStudents = sortedStudents.ThenBy(BuildPredicate(property.Property.Name));
    }
    
    var result = sortedStudents.ToList();
    

    Fix: BuildPredicate can be writen without dynamic. BuildPredicate sample code is changed.

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

Sidebar

Related Questions

I'm trying to build a regular expression that will catch one of three patterns
I'm trying to build an expression tree ( still ) but getting further! I
I'm trying to build s-expression objects using boost::proto with the following terminals: typedef proto::terminal<
I am trying to build a regular expression in javascript that checks for 3
I have been trying to build a regular expression but haven't been able to
I am using cmake-gui trying to build opencv but get this error: CMake Error
I am trying to build up an expression that will be applied to an
I am trying to build a scanner for AWK source code using (F)Lex analysis.
I'm trying to build a regular expression that matches regular expressions between two forward
I'm trying to build a parser that can take a human language expression like

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.