colinfang
colinfang

Reputation: 21727

would it be bad practice to add select to shorten Linq query?

for example

Originally:

 var query = A.Where(x=>criteriaA(x.item2).Where(x=>criteriaB(x.item2))
              .Where(x=>criteriaC(x.item2))).Select(x=>x.item2);

What if:

var B = A.Select(x=>x.item2)
var query = B.Where(x=>criteriaA(x)
             .Where(x=>criteriaB(x)).Where(x=>criteriaC(x)));

Upvotes: 0

Views: 133

Answers (4)

Muttok
Muttok

Reputation: 671

Linq queries could be written in many ways, but I prefer to keep them as readable as possible.

I would prefer something like:

var query = from x in A
            where criteriaA(x) && criteriaB(x) && criteriaC(x)
            select x;

Upvotes: 0

Random Dev
Random Dev

Reputation: 52280

it's fine - what about

var query = A.Select(x=>x.item2)
             .Where(item2=>   criteriaA(item2)
                           && criteriaB(item2) 
                           && criteriaC(item2));

Upvotes: 3

Bob Vale
Bob Vale

Reputation: 18474

There would be little difference and should have similar performance characteristics. I've also checked in linq pad and the resultant SQL for linq to SQL is identical

You can shorten the query further with either

var B = A.Select(x=>x.item2)  
var query = B.Where(x=>criteriaA(x) && criteriaB(x) && criteriaC(c));

or

var B = A.Select(x=>x.item2)  
var query = B.Where(criteriaA).Where(criteriaB).Where(criteriaC);  

Upvotes: 1

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234484

They produce the same result, and I expect them to have very similar performance characteristics. The second has a little less duplication, so I'd prefer that one. You might even be able to shorten it further to:

var query = A.Select(x=>x.item2)
             .Where(criteriaA).Where(criteriaB).Where(criteriaC);

Or, by collapsing all the predicates:

var query = A.Select(x=>x.item2)
             .Where(x => criteriaA(x) && criteriaB (x) && criteriaC(x));

Upvotes: 0

Related Questions