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 1101343
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T01:01:15+00:00 2026-05-17T01:01:15+00:00

I am attempting to dynamically build up an expression tree so that I can

  • 0

I am attempting to dynamically build up an expression tree so that I can change the sort order for data contained in a dictionary of dictionaries. There is lots of information about dynamically specifying the column to sort by, but this is not really the part I am having problems with. I am struggling with the MethodCallExpression that builds my expression tree.

For purposes of this example, I’ve simplified the dictionary:

Dictionary<string, Dictionary<int, int>> data = new Dictionary<string, Dictionary<int, int>>();

I’m trying to build up an expression that would be the equivilent of something like this:

data.OrderByDescending(someValue)
    .ThenByDescending(someothervalue)
    .ThenByDescending(anothervalue)...etc

Where the number of ‘ThenBy’ or ‘ThenByDescending’ clauses is determined at runtime.

Lets say one example needed to sort by the keys 4, then 3, then 1. I’ve established (I think) that the following expressions translate to my 3 sort orders:

Expression<Func<KeyValuePair<string, Dictionary<int, int>>, int>> ex1 = (r => r.Value[4]);
Expression<Func<KeyValuePair<string, Dictionary<int, int>>, int>> ex2 = (r => r.Value[3]);
Expression<Func<KeyValuePair<string, Dictionary<int, int>>, int>> ex2 = (r => r.Value[1]);

So at compile time I can write this expression and it works fine:

var sortedResults = dic.OrderByDescending(ex1.Compile()).ThenByDescending(ex2.Compile()).ThenByDescending(ex3.Compile());

However since the number of sort expressions will vary at runtime I need to build this dynamically, which is where I am struggling.
I am aware that query expressions can be built up at runtime using MethodCallExpression. The MSDN example shows this:

    // ***** OrderBy(company => company) *****
    // Create an expression tree that represents the expression
    // 'whereCallExpression.OrderBy(company => company)'
    MethodCallExpression orderByCallExpression = Expression.Call(
        typeof(Queryable),
        "OrderBy",
        new Type[] { queryableData.ElementType, queryableData.ElementType },
        whereCallExpression,
        Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe }));
    // ***** End OrderBy *****

However, I just can’t make the transition from this example, to my dictionary of dictionaries that uses this:

Func<KeyValuePair<string, Dictionary<int, int>>, int>

What I think I need to do is write something like this (this is in partial psuedo code):

    private static void Test()
    {
        var query = data.AsQueryable()
        foreach (int key in ListOfRequiredKeys)
        {
            Expression<Func<KeyValuePair<string, Dictionary<int, int>>, int>> exp = (r => r.Value[key]);
            MakeQuery(exp, query);
        }        
    }   

    private static IQueryable MakeQuery(Expression<Func<KeyValuePair<string, Dictionary<int, int>> exp, IQueryable query)
    {
        MethodCallExpression orderByCallExpression = Expression.Call(
        typeof(Queryable),
        "ThenBy",
        new Type[] { query.ElementType, query.ElementType },
        query.Expression,
        Expression.Lambda<Expression<Func<KeyValuePair<string, Dictionary<int, int>>>(exp));
    }

I know that isn’t the correct syntax, but it should indicate my thinking. Can some one advise how to move from the MSDN example, to dynamically sort this dictionary of dictionaries?

Thanks
Jason

  • 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-17T01:01:16+00:00Added an answer on May 17, 2026 at 1:01 am

    You can write

    var result = data.OrderByDescending(someValue)
                     .ThenByDescending(someothervalue)
                     .ThenByDescending(anothervalue); //...etc
    

    as

    var result = data.OrderByDescending(someValue);
    result = result.ThenByDescending(someothervalue);
    result = result.ThenByDescending(anothervalue);
    //...etc
    

    So you just need to call OrderBy(Descending) to get an IOrderedEnumerable/Queryable and can then repeated call ThenBy(Descending) on it.

    private static void Test()
    {
        var query = data.AsQueryable();
    
        var f = ListOfRequiredKeys.First();
        var orderedQuery = query.OrderBy(r => r.Value[f]);
    
        foreach (int key in ListOfRequiredKeys.Skip(1))
        {
            var k = key;
            orderedQuery = orderedQuery.ThenBy(r => r.Value[k]);
        }        
    }   
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

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.