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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T08:09:57+00:00 2026-06-04T08:09:57+00:00

I’m in the process of creating a more elaborate filtering system for this huge

  • 0

I’m in the process of creating a more elaborate filtering system for this huge project of ours. One of the main predicates is being able to pass comparations through a string parameter. This expresses in the following form: “>50” or “5-10” or “<123.2”

What I have (as an example to illustrate)

ViewModel:

TotalCost (string) (value: "<50")
Required (string) (value: "5-10")

EF Model:

TotalCost (double)
Required(double)

Expression that I would like to use:

model => model.Where(field => field.TotalCost.Compare(viewModel.TotalCost) && field.Required.Compare(viewModel.Required));

Expression that I would like to receive:

model => model.Where(field => field.TotalCost < 50 && field.Required > 5 && field.Required < 10);

Or something akin to that

However… I have no idea where to start. I’ve narrowed it down to

public static Expression Compare<T>(this Expression<Func<T, bool>> value, string compare)

It may not be even correct, but this is about all I have. The comparison builder is not the issue, that’s the easy bit. The hard part is actually returning the expression. I have never tried returning expressions as function values. So basically what I need to keep, is the field and return a comparison expression, pretty much.

Any help? 😡

Update:

Alas this doesn’t solve my problem. It may be because I have been up for the past 23 hours, but I have not the slightest clue on how to make it into an extension method. As I said, what I’d like… is basically a way to write:

var ex = new ExTest();
var items = ex.Repo.Items.Where(x => x.Cost.Compare("<50"));

The way I shaped out that function (probably completely wrong) is

public static Expression<Func<decimal, bool>> Compare(string arg)
{
    if (arg.Contains("<"))
        return d => d < int.Parse(arg);

    return d => d > int.Parse(arg);
}

It’s missing the “this -something- value” to compare to in first place, and I haven’t managed to figure out yet how to have it be able to get an expression input… as for ReSharper, it suggests me to convert it to boolean instead…

My head’s full of fluff at the moment…

Update 2:

I managed to figure out a way to have a piece of code that works in a memory repository on a console application. I’m yet to try it with Entity Framework though.

public static bool Compare(this double val, string arg)
    {
        var arg2 = arg.Replace("<", "").Replace(">", "");
        if (arg.Contains("<"))
            return val < double.Parse(arg2);

        return val > double.Parse(arg2);
    }

However, I highly doubt that’s what I’m after

Update 3:

Right, after sitting down and looking through lambda expressions again, before the last answer, I came up with something akin to the following, it doesn’t fill in the exact requirements of “Compare()” but It’s an ‘overload-ish’ Where method:

public static IQueryable<T> WhereExpression<T>(this IQueryable<T> queryable, Expression<Func<T, double>> predicate, string arg)
    {
        var lambda =
            Expression.Lambda<Func<T, bool>>(Expression.LessThan(predicate.Body, Expression.Constant(double.Parse(50.ToString()))));

        return queryable.Where(lambda);
    }

However, despite to my eyes, everything seeming logical, I get runtime exception of:

System.ArgumentException was unhandled
  Message=Incorrect number of parameters supplied for lambda declaration
  Source=System.Core
  StackTrace:
       at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type delegateType, Expression& body, ReadOnlyCollection`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, Boolean tailCall, IEnumerable`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, ParameterExpression[] parameters)

This being the culprit line obviously:

var lambda =
                Expression.Lambda<Func<T, bool>>(Expression.LessThan(predicate.Body, Expression.Constant(double.Parse(50.ToString()))));

I’m very close to the solution. If I can get that error off my back, I believe EF should be capable of translating that into SQL. Otherwise… well, the last response will probably go.

  • 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-04T08:09:58+00:00Added an answer on June 4, 2026 at 8:09 am

    To generate expression, that would be translated to SQL (eSQL) you should generate Expression manually. Here is example for GreaterThan filter creating, other filters can be made with similar technique.

    static Expression<Func<T, bool>> CreateGreaterThanExpression<T>(Expression<Func<T, decimal>> fieldExtractor, decimal value)
    {
        var xPar = Expression.Parameter(typeof(T), "x");
        var x = new ParameterRebinder(xPar);
        var getter = (MemberExpression)x.Visit(fieldExtractor.Body);
        var resultBody = Expression.GreaterThan(getter, Expression.Constant(value, typeof(decimal)));
        return Expression.Lambda<Func<T, bool>>(resultBody, xPar);
    }
    
    private sealed class ParameterRebinder : ExpressionVisitor
    {
        private readonly ParameterExpression _parameter;
    
        public ParameterRebinder(ParameterExpression parameter)
        { this._parameter = parameter; }
    
        protected override Expression VisitParameter(ParameterExpression p)
        { return base.VisitParameter(this._parameter); }
    }
    

    Here is the example of usage. (Assume, that we have StackEntites EF context with entity set TestEnitities of TestEntity entities)

    static void Main(string[] args)
    {
        using (var ents = new StackEntities())
        {
            var filter = CreateGreaterThanExpression<TestEnitity>(x => x.SortProperty, 3);
            var items = ents.TestEnitities.Where(filter).ToArray();
        }
    }
    

    Update:
    For your creation of complex expression you may use code like this:
    (Assume have already made CreateLessThanExpression and CreateBetweenExpression functions)

    static Expression<Func<T, bool>> CreateFilterFromString<T>(Expression<Func<T, decimal>> fieldExtractor, string text)
    {
        var greaterOrLessRegex = new Regex(@"^\s*(?<sign>\>|\<)\s*(?<number>\d+(\.\d+){0,1})\s*$");
        var match = greaterOrLessRegex.Match(text);
        if (match.Success)
        {
            var number = decimal.Parse(match.Result("${number}"));
            var sign = match.Result("${sign}");
            switch (sign)
            {
                case ">":
                    return CreateGreaterThanExpression(fieldExtractor, number);
                case "<":
                    return CreateLessThanExpression(fieldExtractor, number);
                default:
                    throw new Exception("Bad Sign!");
            }
        }
    
        var betweenRegex = new Regex(@"^\s*(?<number1>\d+(\.\d+){0,1})\s*-\s*(?<number2>\d+(\.\d+){0,1})\s*$");
        match = betweenRegex.Match(text);
        if (match.Success)
        {
            var number1 = decimal.Parse(match.Result("${number1}"));
            var number2 = decimal.Parse(match.Result("${number2}"));
            return CreateBetweenExpression(fieldExtractor, number1, number2);
        }
        throw new Exception("Bad filter Format!");
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I am reading a book about Javascript and jQuery and using one of the
I have this code to decode numeric html entities to the UTF8 equivalent character.
In my XML file chapters tag has more chapter tag.i need to display chapters
This could be a duplicate question, but I have no idea what search terms
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

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.