John
John

Reputation: 47

conditional test if integer is equivalent to a set of known integer constants C#

I am trying to write a conditional to determine if an unknown integer 'a' is equivalent to a set of known constants, x, y or z. In some languages, like delphi this can be done as follows:

if (a in [x, y, z]) then
begin
   //do something
end;

I am working in C#, however, so this does not work. There are obvious ways to do it but I have been unable to find an equivalently simple way to do it and was wondering if one exists.

Thanks for ahead of time for any suggestions.

Upvotes: 0

Views: 90

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502406

You could use:

if (new[] { x, y, x }.Contains(a))

(Note that this requires either LINQ to Objects and a using directive of using System.Linq; or an ugly cast to ICollection<int>.)

Or better, just create the set once, e.g.

private static readonly HashSet<int> ValidValues = new HashSet<int> { 1, 2, 3 };

...

if (ValidValues.Contains(a))

If the number of elements is fairly small, then actually an array may well be faster than a HashSet:

private static readonly int[] ValidValues = { 1, 2, 3 };

Or wrap it in a read-only collection if you don't trust yourself not to modify it in your class.

Upvotes: 3

Ken Browning
Ken Browning

Reputation: 29101

If you're using LINQ then this should work for you:

if (new[] { x, y, z }.Contains(a))

If you're not using LINQ then this would also be equiv:

if (-1 != Array.IndexOf(new[] { x, y, z }, a))

Upvotes: 2

Related Questions