Most succinct way to determine if a variable equals a value from a 'list' of values
-
09-06-2019 - |
Question
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);
Solution
bool b = new int[] { 3,7,12,5 }.Contains(5);
OTHER TIPS
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 };
Since you did not specify what type of data you have as input I'm going to assume you can partition your input into powers of 2 -> 2,4,8,16... This will allow you to use the bits to determine if your test value is one of the bits in the input.
4 => 0000100
16 => 0010000
64 => 1000000
using some binary math...
testList = 4 + 16 + 64 => 1010100
testValue = 16
testResult = testList & testValue