Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor LINQ select statement

Given the following LINQ statement, can someone tell me if it is possible to refactor the select portion into an expression tree? I have not used expression tree's before and have not been able to find much information regarding Selects.. Note this is to be translated into SQL and run inside SQL Server, not in memory.

var results = db.Widgets
    .Select(w => new
    {
        Name = (w is x) ? "Widget A" : "Widget B"
    });

I would like to be able to do this..

var name = [INSERT REUSABLE EXPRESSION]
var somethingElse = [INSERT REUSABLE EXPRESSION]
var results = db.Widgets.Select(w => new { Name = name, SomethingElse = somethingElse });

Obviously the intended use is for more complex statements.

like image 424
Grant Avatar asked Feb 02 '26 05:02

Grant


1 Answers

You can do this using LinqKit. It'll work as long as your method is translatable to SQL. This is essentially what a complete example might look like:

public static class ReusableMethods
{
    public static Expression<Func<int, Person>> GetAge()
    {
        return p => p.Age;
    }
}

var getAge = ReusableMethods.GetAge();
var ageQuery = from p in People.AsExpandable()
               select getAge.Invoke(p);

Note that:

  1. You need to add AsExpandable() to your IQueryable.
  2. You must assign your method to a local variable before using it (not sure about the exact reason why, but its a must).
like image 151
Ocelot20 Avatar answered Feb 05 '26 00:02

Ocelot20



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!