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=>criter开发者_运维问答iaB(x)).Where(x=>criteriaC(x)));
it's fine - what about
var query = A.Select(x=>x.item2)
.Where(item2=> criteriaA(item2)
&& criteriaB(item2)
&& criteriaC(item2));
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);
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));
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;
精彩评论