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?
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 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.
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.
Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With