Nate Pet
Nate Pet

Reputation: 46222

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?

Upvotes: 0

Views: 128

Answers (3)

Jon Egerton
Jon Egerton

Reputation: 41539

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.

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

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

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499800

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.

Upvotes: 5

Related Questions