Expression.Lambda and query generation at runtime, simplest “Where” example

后端 未结 1 1845
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 11:11

I was trying to generate a simple Lambda Expression at runtime with no luck... something like this:

var result = queryableData.Where(item => item.Name ==          


        
相关标签:
1条回答
  • 2020-11-27 11:25

    In the following query

    var result = query.Where(item => item.Name == "Soap")
    

    the lambda expression is

    item => item.Name == "Soap"
    

    You only need to construct this part, not the Where call which accepts an expression tree.

    The expression tree for the lambda expression looks like this:

                         Lambda
                          /  \
                       Equal  Parameter
                       /   \    item
                  Property  \
                   "Name"   Constant
                     |       "Soap"
                 Parameter         
                   item
    

    In code:

    var item = Expression.Parameter(typeof(Item), "item");
    
    var prop = Expression.Property(item, "Name");
    
    var soap = Expression.Constant("Soap");
    
    var equal = Expression.Equal(prop, soap);
    
    var lambda = Expression.Lambda<Func<Item, bool>>(equal, item);
    
    var result = queryableData.Where(lambda);
    
    0 讨论(0)
提交回复
热议问题