If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?
I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.
I know I could do something like this:
int baseCase = 5;
bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5;
I'm curious to see if I could do something more like this:
int baseCase = 5;
bool testResult = baseCase == (3 | 7 | 12 | 5);
Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.
UPDATE:
I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.
Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of:
new List<int>(new int[] { 3, 6, 7, 1 }).Contains(5);
bool b = new int[] { 3,7,12,5 }.Contains(5);
You can do something similar with .NET 2.0, by taking advantage of the fact that an array of T implements IList<T>, and IList<T> has a Contains method. Therefore the following is equivalent to Corey's .NET 3.5 solution, though obviously less clear:
bool b = ((IList<int>)new int[] { 3, 7, 12, 5 }).Contains(5);
I often use IList<T> for array declarations, or at least for passing one-dimensional array arguments. It means you can use IList properties such as Count, and switch from an array to a list easily. E.g.
private readonly IList<int> someIntegers = new int[] { 1,2,3,4,5 };
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