Problem: Test if x ∉ { 2, 3, 61, 71 }
I often wondered if there is not a better way than:
if (x != 2 && x != 3 && x != 61 && x != 71)
{
// do things
}
and
if (!new List<int>{ 2, 3, 61, 71 }.Contains(x))
{
// do things
}
The latter one seems quite elegant, but actually it is kind of irritating if you read it, especially because of the inversion. It's kind of an ugly thing because in English we say "x is not element of ...", which is hard to express in C# without irritating overhead. Maybe one coud say if (Object(x).IsElementOf(new[] { ... }))
or so?
Any suggestions? Are there any .Net standard methods to test things like that?
I use an extension method:
using System.Linq;
...
public static bool In<T>(this T item, params T[] list)
{
return list.Contains(item);
}
...
if (!x.In(2,3,61,71))
...
You can rename it to IsElementOf
if you prefer this name...