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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T08:35:52+00:00 2026-05-27T08:35:52+00:00

H. I’m trying to construct linq query that dynamicly generate query for custom ordering

  • 0

H. I’m trying to construct linq query that dynamicly generate query for custom ordering for dynamicly sent field.

I’m construction logic of

Expression<Func<string, int>> SpaceStringSortExpression = (a) => a.StartsWith(" ") ? 2 : 1; 

Signature of this code (SpaceStringSortExpression.ToString()) is “a => IIF(a.StartsWith(\” \”), 2, 1)”

To do that dynamicly I’ve made:

ParameterExpression parameter = Expression.Parameter(typeof(TSource), "p1");
            Expression orderByProperty = Expression.Property(parameter, propertyName);
            ConstantExpression c = Expression.Constant(" ", typeof(string));
            MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
            Expression call = Expression.Call(orderByProperty, mi, c);
            Expression<Func<TSource, bool>> lambda = Expression.Lambda<Func<TSource, bool>>(call, parameter);
            ConditionalExpression t = Expression.IfThenElse(call, Expression.Constant(2), Expression.Constant(1));
            //t.tostring() - IIF(p1.Login.StartsWith(" "), 2, 1)
            LambdaExpression callt = Expression.Lambda(t, new[] { parameter });
            //callt.tostring() = p1 => IIF(p1.Login.StartsWith(" "), 2, 1)

But I can’t make it work passing the result to OrderBy

MethodInfo genericMethod;

            genericMethod = OrderByMethod.MakeGenericMethod

            genericMethod = OrderByDescendingMethod.MakeGenericMethod
           (new[] { typeof(TSource), typeof(Int32) });

        object ret = genericMethod.Invoke(null, new object[] { source, callt });
        return (IQueryable<TSource>)ret;

And I’ve got (translated from locolised IIS)

Unable to convert "System.Linq.Expressions.Expression`1[System.Action`1[XXXX.User]]" to type "System.Linq.Expressions.Expression`1[System.Func`2[XXXX.User,System.Int32]]".

The whole code is:

public static IQueryable<TSource> OrderByPropertyRegardingWhiteSpaces<TSource>
        (this IQueryable<TSource> source, string propertyName, bool ascDirection = true)
        {
  ParameterExpression parameter = Expression.Parameter(typeof(TSource), "p1");
            Expression orderByProperty = Expression.Property(parameter, propertyName);
            ConstantExpression c = Expression.Constant(" ", typeof(string));
            MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
            Expression call = Expression.Call(orderByProperty, mi, c);
            Expression<Func<TSource, bool>> lambda = Expression.Lambda<Func<TSource, bool>>(call, parameter);
            ConditionalExpression t = Expression.IfThenElse(call, Expression.Constant(2), Expression.Constant(1));
            //t.tostring() - IIF(p1.Login.StartsWith(" "), 2, 1)
            LambdaExpression callt = Expression.Lambda(t, new[] { parameter });
            //callt.tostring() = p1 => IIF(p1.Login.StartsWith(" "), 2, 1)
MethodInfo genericMethod;
genericMethod = OrderByMethod.MakeGenericMethod
                (new[] { typeof(TSource), typeof(Int32) });
object ret = genericMethod.Invoke(null, new object[] { source, callt });
            return (IQueryable<TSource>)ret;
   }



        private static readonly MethodInfo OrderByMethod =
        typeof(Queryable).GetMethods()
            .Where(method => method.Name == "OrderBy")
            .Where(method => method.GetParameters().Length == 2)
            .Single();

Could anyone help me with this?

the simplier example (just sort by dynamic parametr) is working fine:

public static IQueryable<TSource> OrderByProperty<TSource>
        (this IQueryable<TSource> source, string propertyName, bool ascDirection = true)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(TSource), "p1");
            Expression orderByProperty = Expression.Property(parameter, propertyName);

            LambdaExpression call = Expression.Lambda(orderByProperty, new[] { parameter });
MethodInfo genericMethod;
            if (ascDirection)
            {
                genericMethod = OrderByMethod.MakeGenericMethod
                (new[] { typeof(TSource), orderByProperty.Type });
            }
            else
            {
                genericMethod = OrderByDescendingMethod.MakeGenericMethod
               (new[] { typeof(TSource), orderByProperty.Type });
            }
            object ret = genericMethod.Invoke(null, new object[] { source, call });
            return (IQueryable<TSource>)ret;
        }
  • 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-27T08:35:53+00:00Added an answer on May 27, 2026 at 8:35 am

    The problem is that this:

    ConditionalExpression t = Expression.IfThenElse(call, Expression.Constant(2), Expression.Constant(1));
    

    becomes an expression of type Action, the expressions for “then” and “else” are executed but do not return a value as you intended. This doesn’t match the signature desired by the OrderBy method, so it throws the exception you are seeing. You want this:

    ConditionalExpression t = Expression.Condition(call, Expression.Constant(2), Expression.Constant(1));
    

    The Condition node type has a return value. A great way to debug this is to write a unit test that does this:

    Expression<Func<bool,int>> expr = (a) => a ? 2 : 1
    

    and then use the debugger to examine the expression tree that was generated. Hope that helps.

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

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.