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.
You could use:
(Note that this requires either LINQ to Objects and a
usingdirective ofusing System.Linq;or an ugly cast toICollection<int>.)Or better, just create the set once, e.g.
If the number of elements is fairly small, then actually an array may well be faster than a
HashSet:Or wrap it in a read-only collection if you don’t trust yourself not to modify it in your class.