DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

C#: Pass Lambda Expression to Where LINQ at Runtime

I often use LINQ query in my projects, and I sometime needs to pass the lambda expression at the run time, rather than compile time. In this article, I show some samples to achieve this.

Install Library

I create a console application with .NET 7 this time. One library I need to include is System.Linq.Dynamic.Core.

Where LINQ

Let's write a code for Where LINQ query. The Where extension method takes Func<T, bool> delegate. The T changes depending on what you query against.

I use List<string> to simplify the sample for now.

  • Define input type and variable name as ParameterExpression
  • Define expression and return type
  • Define lambda


ParameterExpression param = Expression.Parameter(typeof(string), "x");
Expression expression = new ExpressionParser(
    new ParameterExpression[] { param }, 
    "x==\"1\"", 
    null, 
    new ParsingConfig())
    .Parse(typeof(bool));

Expression<Func<string, bool>> lambda = 
    Expression.Lambda<Func<string, bool>>(expression, param);


Enter fullscreen mode Exit fullscreen mode

The first statement is to define the input type, which is string and I name it as x.

Then I create the expression as x=="1". The return type is always bool for Where method.

Then finally, create the lambda expression object.

Let's use it.



List<string> inputs = new() { "1", "2" };
List<string>result = inputs.AsQueryable().Where(lambda).ToList();


Enter fullscreen mode Exit fullscreen mode

This is equivalent to inputs.Where(x=>x == "1").ToList().

The result is:

Image description

Now, change it to dynamic by using Console.ReadLine();



string query = Console.ReadLine();

ParameterExpression param = Expression.Parameter(typeof(string), "x");
Expression expression = new ExpressionParser(
    new ParameterExpression[] { param },
    query, 
    null, 
    new ParsingConfig())
    .Parse(typeof(bool));


Enter fullscreen mode Exit fullscreen mode

Then, I can pass query from console.

Image description

Summary

I hope you get some idea how to dynamically create the lambda expression object. In the next article, I will show other LINQ examples.

Top comments (0)