Is there any disadvantage in concatenating multiple Where
in LINQ instead of using a single Where
with multiple conditions?
I'm asking because using multiple Where
can help to reduce complexity and improve maintainability of my code considerably.
Consider following code, chargeList
is a List<Charge>
which is the source of a BindingSource
:
IEnumerable<Charge> matchingCharges = chargeList;
if(!string.IsNullOrWhiteSpace(channelAbbr))
matchingCharges = matchingCharges
.Where(c => c.ChannelAbbreviation == channelAbbr);
if(deliveryNoteDate.HasValue)
matchingCharges = matchingCharges
.Where(c => c.ArrivalAt == deliveryNoteDate.Value);
if(chargeID.HasValue)
matchingCharges = matchingCharges
.Where(c => c.ChargeID == chargeID.Value);
This concise code will handle all combinations of filter, none,one,two,all.
Otherwise i'd have to use if-else
and multiple conditions in a single Where
.
This is the best that comes to my mind:
// important to keep code readable:
bool filterChannel = !string.IsNullOrWhiteSpace(channelAbbr);
bool filterDate = deliveryNoteDate.HasValue;
bool filterID = chargeID.HasValue;
if(!filterChannel && !filterDate && !filterID)
{
// take all
matchingCharges = chargeList;
}
else
{
matchingCharges = chargeList
.Where(c =>
filterChannel ? c.ChannelAbbreviation == channelAbbr : true
&& filterDate ? c.ArrivalAt == deliveryNoteDate.Value : true
&& filterID ? c.ChargeID == chargeID.Value : true);
}
So what are the differences between both, are they negligible? Does the LINQ provider matter?
Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.
you can use && and write all conditions in to the same where clause, or you can . Where().
Yes, it's slower.
Single() returns the only element from a collection, or the only element that satisfies the specified condition. If a given collection includes no elements or more than one elements then Single() throws InvalidOperationException.
Semantically, there is no difference in the case of Where
(contrast OrderBy
, which needs more care). At the implementation level, it is simply multiple predicates with simple expression trees instead of a single predicate with a complex expression tree; but most engines will cope fine with either.
For what you are doing, multiple Where
is ideal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With