0

I am new to Expressions in c#.

Expression code

var parameter = Expression.Parameter(typeof(int), "param");
var constant = Expression.Constant(5, typeof(int));
var equal = Expression.Equal(parameter, constant);
var lambdaExpression = Expression.Lambda<Func<int, bool>>(equal, parameter);
var compiledExpression = lambdaExpression.Compile();

Query contains a string value and I want to apply expresion only if the value is convertible to int

int test;
query = query.Where(i => int.TryParse(i.Key, out test) && compiledExpression(test));

This returns an error saying int.TryParse is not supported. Any way to solve this?

10
  • What type of object is query? Commented Aug 25, 2016 at 21:16
  • It is a Queryable object @SledgeHammer Commented Aug 25, 2016 at 21:17
  • What is the exact and complete error message? Commented Aug 25, 2016 at 21:20
  • Is query a LINQ to SQL query? Commented Aug 25, 2016 at 21:23
  • If it is a LINQ to SQL query, then you cannot use a compiled expression. Commented Aug 25, 2016 at 21:26

2 Answers 2

1

You can't use out parameters there.

1) var v = q.Where(x => x.All(c => c >= '0' && c <= '9'));
2) use regex instead of All
3) write a simple method that calls Int32.Parse and just returns a bool to hide the out param

for #3:

    static bool SafeIntParse(string s)
    {
        int n;
        return Int32.TryParse(s, out n);
    }

    var v = q.Where(x => SafeIntParse(x));

The SafeIntParse() method is, of course, a separate static method.

EDIT:

for the regex method:

        Regex regex = new Regex("^\\d+$", RegexOptions.Compiled);
        var v = q.Where(x => regex.Match(x).Success);

Of course, make the regex object a static object of the class.

Sign up to request clarification or add additional context in comments.

2 Comments

Part (2) is not clear. I tried (3) but it throws error lambda expressions are not allowed @sledgehammer
Sorry, if I was not clear. What I meant was can please elaborate Part2 use regex instead of all. Where and how? @sledgehammer
0

You can implement your own function to get the value, int.TryParse returns 0 by default if the string cannot be converted.

Here you have

private decimal GetDecimal(string value)
{
    if(decimal.TryParse(value, out decimal result))
        return result;
    return 0;
}

1 Comment

Please see the comments. It's a query that should be translated into SQL. Calling GetDecimal instead of int.TryParse isn't supported either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.