[英]Linq most efficient way
I was wondering if there is a more efficient way of doing what I need done below: 我想知道下面是否有更有效的方法来完成我需要做的事情:
return HttpContext.Current.User.IsInRole("Admin")
? dbContext.Prog_Search1(searchField, searchString, searchOper).Where(a => a.Id == 2)
: dbContext.Prog_Search1(searchField, searchString, searchOper).Where(a => a.Id == 1)
I was wondering if there is a clever way of using just one 我想知道是否只有一种聪明的使用方式
dbContext.Search1(searchField, searchString, searchOper)
versus the 2 that I am using and then doing a Where clause conditionally? 与我正在使用的2,然后有条件地执行Where子句?
Yes, it sounds like you want something like: 是的,听起来您想要这样的东西:
int targetId = HttpContext.Current.User.IsInRole("Admin") ? 2 : 1;
return dbContext.Prog_Search1(searchField, searchString, searchOper)
.Where(a => a.Id == targetId);
Note that this doesn't really change the efficiency , but it does affect the readability. 请注意,这并没有真正改变效率 ,但确实会影响可读性。
I think you want something like this: 我想你想要这样的东西:
var id = HttpContext.Current.User.IsInRole("Admin") ? 2 : 1
return dbContext.Prog_Search1(searchField, searchString, searchOper)
.Where(a => a.Id == id);
Alternatively: 或者:
var srch = dbContext.Prog_Search1(searchField, searchString, searchOper);
return HttpContext.Current.User.IsInRole("Admin")
? srch.Where(a => a.Id == 2)
: srch.Where(a => a.Id == 1);
Is less tidy in your particular instance than just pre-setting i=1 or 2
, but more flexible generally should the two different Where
commands be more different. 在您的特定实例中,它的整洁性不只是预先设置
i=1 or 2
,而是通常应该在两个不同的Where
命令之间的差异更大时更加灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.