I’ve got this enum flag:
[Flags()]
public enum Levels
{
Beginner, Medium, Advanced, Master
}
I’ve got a property called Bank, where this is a Dictionary<Levels, ...> and Levels are the possible options that you can choose
Let’s go to suppose that my first KeyValuePair contains the following Key = Levels.Beginner | Levels.Medium | Levels. Advanced. So the idea if I enter in the dictionary Levels.Medium, returns me the last object because Medium is a possible value.
public Worksheet LoadWorksheet(Levels level)
{
Worksheet worksheet = new Worksheet(this.Bank[level].Value, this.Bank[level].Key);
return worksheet;
}
But unfortunatly, when I do this, throws me an error pointing that the key does not exist. How can I do to match the key?
First, I should point out that if:
then:
When looking up values in the dictionary, the dictionary first uses the hash value of the key to determine the correct bucket, and then uses equality comparison to identify the right key in the bucket.
If the hash values are not equal then the key will not be found. If the key values are not equal, then the value will not be found.
You can get all entries that have a key containing
Levels.Mediumby seeing if it’s bit pattern is present in the key with the following LINQ expression:Or, as @Ria pointed out, in .Net 4 you can use the HasFlags member:
The good point was made in another answers (@dasblinkenlight, @Ria) that the values of your enumeration need to have non-overlapping bit patterns for this to work: