Define part of an Expression as a variable in c#

后端 未结 4 563
有刺的猬
有刺的猬 2020-12-19 10:49

I have following code:

public class MyClass
{
   Expression> Criteria {get; set;}
}
public class Customer
{
   //..
   publ         


        
4条回答
  •  一个人的身影
    2020-12-19 11:02

    If you want an expression, then you can use LinqKit to do the following:

    Expression> p = x => x.Name;
    
    var c = new MyClass();
    
    c.Criteria = x => p.Invoke(x).StartsWith("asd"); //Reuse p expression
    
    c.Criteria = c.Criteria.Expand();
    

    Invoke is an extension method provided by LinqKit that helps you to compose expressions easily.

    After invoking the Expand method, c.Criteria would contain an expression that is exactly the same as if you have done this:

    c.Criteria = x => x.Name.StartsWith("asd");
    

提交回复
热议问题