With a linq query I retrieve a list from the database. The list contains 2 items of a specific class containing the property RoleType. the type of RoleType is an int.
the first object has a property value 0. the second object has a property value 1.
I also got an enum:
enum RoleTypes
{
Type1 = 1,
Type2 = 0,
}
The weird order of indexing the enums is a given, I can't change that.
My business rules states that there has to be exactly one role with RoleType value Type2 and at least one role with RoleType value Type1. This is the code I use for that:
var ExactlyOneRoleType2 = roles.Count(role => role.RoleType == (int)RoleTypes.Type2) == 1;
var AtLeastOneRoleType1 = roles.Any(role => role.RoleType == (int)RoleTypes.Type1);
According to the list I mentioned earlier, both variables (ExactlyOneRoleType2 and AtLeastOneRoleType1) should be true. At least, I would expect that. Only if I debug through the code I found out that ExactlyOneRoleType2 is false. After some research I find out that
roles.Count(role => role.RoleType == (int)RoleTypes.Type2)
returns 2 instead of 1 which I find odd because there is only 1 role with RoleType Type2. Why does the count return 2? It also doesn't compute with the fact that the Any call actually returns true. How can list containing 2 items have both 2 items with RoleType Type2 and have at least one item with RoleType Type1?
Also when I change the count call to
roles.Count(role => role.RoleType == 0)
it still returns 2. Only when I change the Count call to this:
private static bool IsRoleTypeType2(Role role)
{
return role.RoleType == (int)RoleTypes.Type2;
}
roles.Count(IsRoleTypeType2)
the count returns 1 as it should be.
What is happening here? Why does the count return 2 when I use a anonymous predicate? Did I misunderstood something about how the predicate works in case of count? Or is this is bug in Linq?