how can i store and reuse pieces of my lambda expressions

前端 未结 3 1019
谎友^
谎友^ 2021-02-19 19:18

I have a block of code where a piece of the lambda expression is used again and again. How can store this logic so that i can reuse this expression piece?

Eg: lets take

3条回答
  •  情话喂你
    2021-02-19 20:06

    You haven't told us if the lambda expressions are being converted to expression-trees or to delegates, but assuming the former, I recommend using PredicateBuilder.

    Expression predicate = map =>  map.User.Key == _users.PublicUser.Key 
                                           || map.User.Key == _users.CurrentUser.Key;
    

    Then your first query becomes:

    var pred1 = predicate.And
                (map => map.AccessLevel.ToAccessLevel() == AccessLevel.Write);
    
    var query1 = Session.Query
        (dimgroup => dimgroup.Users.Where(pred1).Count() > 0);
    

    And your second:

    var pred2 = predicate.And
                (map => map.AccessLevel.ToAccessLevel() == AccessLevel.Read);
    
    var query2 = Session.Query
        (dimgroup => dimgroup.Users.Where(pred2).Count() > 0);
    

    As you can see, there is scope for factoring out even more commonalities; since the queries appear to only differ by different AccessLevels.

提交回复
热议问题