简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM