0

I am starting to see methods like the one below used more and more, but it's a concept that I don't fully understand.

    public virtual Task<List<T>> GetAsync(Expression<Func<T, bool>> exp)
    {
        using (var conn = _factory.OpenDbConnection())
        {
            return conn.SelectAsync(exp);
        }
    }

Can someone help me translate the method parameter there that is an Expression? Like explain it as how it differs from a standard instance parameter?

Paul Duer
  • 1,100
  • 1
  • 13
  • 32

1 Answers1

1

These are called Expression Trees (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/).

Basically it's a lamdba that can be translated to another platform, from the looks of it some kind of database in your case. This function would be translated (by a library) to SQL and then executed in the database.

Within the code of your program you would generally only need lambdas (Func<>), but in some cases you need an Expression Tree. Besides your example, sometimes you need a dynamically constructed function which can be done using these.

General information on lambdas can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions

Aage
  • 5,932
  • 2
  • 32
  • 57