我如何存储和重用我的lambda表达式 [英] how can i store and reuse pieces of my lambda expressions

查看:105
本文介绍了我如何存储和重用我的lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,其中一次又一次使用了一部分lambda表达式.如何存储此逻辑,以便我可以重用此表达式?

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)是我要重用的部分.

和类似的代码...

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)是我要重用的部分.

(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?

推荐答案

最简单的方法是重用单个lamda表达式,如下所示:

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
));

下一步是通过调用lambda表达式来实际修改表达式树本身.这更加复杂,并且除非您想了解它,否则使用工具箱将更容易.我建议 LinqKit .

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.

这篇关于我如何存储和重用我的lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆