Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i store and reuse pieces of my lambda expressions

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 the example of the code given below

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

(map.User.Key == _users.PublicUser.Key || map.User.Key == _users.CurrentUser.Key) being the portion I want to reuse.

and a similar piece of code...

Session.Query<DimensionGroup>()(dimgroup =>(dimgroup.Users.Where(map => ((map.User.Key
==_users.PublicUser.Key || map.User.Key == _users.CurrentUser.Key) &&
map.AccessLevel.ToAccessLevel() ==  AccessLevel.Read)).Count() > 0));

(map.User.Key == _users.PublicUser.Key || map.User.Key == _users.CurrentUser.Key) being the portion I want to reuse.

Is there some way I can reuse just those parts of the expression?

like image 499
Whimsical Avatar asked Mar 22 '11 19:03

Whimsical


People also ask

How do you reuse lambda expression?

One way I can reuse this lambda expression is if there is some interface/class which is a parent of all lambda expressions such that I can assign any lambda expression to a reference of such an interface/class.

Can lambda function be reused in python?

Can we reuse the lambda function? I guess the answer is yes because in the below example I can reuse the same lambda function to add the number to the existing numbers.

How are lambdas stored?

The Lambda service stores your function code in an internal S3 bucket that's private to your account. Each AWS account is allocated 75 GB of storage in each Region. Code storage includes the total storage used by both Lambda functions and layers.

Can u use lambda function for doing multiple expression?

Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.


1 Answers

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

Expression<Func<User, bool>> KeysMatch = 
    map => map.User.Key == _users.PublicUser.Key 
        || map.User.Key == _users.CurrentUser.Key;

Session.Query<DimensionGroup>()(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.

like image 171
Chris Pitman Avatar answered Oct 12 '22 22:10

Chris Pitman