how can i store and reuse pieces of my lambda expressions

前端 未结 3 951
谎友^
谎友^ 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 19:54

    The easiest way is to reuse a single lamda expression, like so:

    Expression> KeysMatch = 
        map => map.User.Key == _users.PublicUser.Key 
            || map.User.Key == _users.CurrentUser.Key;
    
    Session.Query()(dimgroup=>(
        dimgroup.Users.Where(KeysMatch)
        .Where(map => map.AccessLevel.ToAccessLevel() == AccessLevel.Write))
        .Count() > 0
    ));
    

    The next step up is to actually modify expression trees themselves by invoking lambda expressions. This is more complicated, and unless you want to get down and dirty with it is easier with a toolkit. I suggest LinqKit.

提交回复
热议问题