Asked • 07/13/19

Most succinct way to determine if a variable equals a value from a 'list' of values?

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);

1 Expert Answer


Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.