Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an Expression into a LINQ query?

Tags:

c#

linq

I can pass an Expression into the LINQ Select() method:

public IQueryable<T> GetInfo(long limit, Expression<Func<MyType, T>> selector)
{
    return DbSet.Where(t => t.id < limit).Select(selector)
}

How can I do the same using LINQ-style query?

public IQueryable<T> GetInfo(long limit, Expression<Func<MyType, T>> selector)
{
    var result = from t in DbSet
                 where t.id < limit
                 select selector(t) // doesn't work
    return result
}
like image 648
enkryptor Avatar asked Jan 28 '26 02:01

enkryptor


1 Answers

Well you can use:

var result = (from t in DbSet
             where t.id < limit
             select t).Select(selector);

... but you can't just use the selector inside the query expression, as that's implicitly wrapping an extra layer that you don't want.

It's not clear why you want to use query expressions here anyway, mind you - I would strongly recommend that you become comfortable with both styles of LINQ and use whatever's more appropriate at the time - which in this case is the style you have in your original code.

like image 159
Jon Skeet Avatar answered Jan 30 '26 15:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!