tags:

views:

147

answers:

2

Does anyone know if there is a way to test for list membership utilizing a list. For example I have a class named Membership which has a property Rebates which is of type List<Enums.RebateType>. I want to test using a lambda expression to see if that list contains any rebates that are of a specific type. My orginal lambda expression is as follows

return Membership.Rebates.Exists(rebate =>
    rebate.RebateType == Enums.RebateType.A &&
    rebate.RebateStatus == Enums.RebateStatus.Approved);

Instead of having to do the following:

return Membership.Rebates.Exists(rebate =>
   (rebate.RebateType == Enums.RebateType.A &&
    rebate.RebateStatus == Enums.RebateStatus.Approved) ||
   (rebate.RebateType == Enums.RebateType.B &&
    rebate.RebateStatus == Enums.RebateStatus.Approved));

I was wondering if something similar to the following mocked up SQL syntax could be done via one Lambda expression.

SELECT COUNT(*)
FROM Membership.Rebates
WHERE RebateType IN (ValidRebateTypes) AND Approved = true

ValidRebateTypes is curently a List<Enums.RebateType> that I am testing for i.e. ValidRebateTypes = (Enums.RebateType.A, Enums.RebateType.B).

The work around I currently have is as follows:

bool exists = false;
foreach (Enums.RebateType rebateType in ValidRebateTypes())
{
    exists =  Membership.Rebates.Exists(
                rebate =>
                rebate.RebateType == rebateType &&
                rebate.RebateStatus == Enums.RebateStatus.Approved);
    if (exists) { break; }
}
return exists;
+4  A: 
Marc
If all he wants is to know if it exists (not the count) then use `.Any()` instead of `.Count()`, so it can quit at the first match instead of going through the whole shebang.
Daniel Earwicker
Good catch, I was simply duplicating his SQL.
Marc
Or just replace Where with Any and lose the Count altogether.
Daniel Earwicker
(because Any can accept a predicate)
Daniel Earwicker
Edited to consolidate your suggestions.
Marc
+1 good stuff...
Daniel Earwicker
+1  A: 

In addition to Marc's suggestion, I would recomment making ValidRebateTypes a HashSet<Enums.RebateType>. Not only is this likely to be more efficient (although possibly not for a small set), it also reveals your intent (ie. that there only be one of each value of RebateType in it).

Ben Lings