Search code examples
c#.netcoding-style

C#: Most elegant way to test if int x is element of a given set?


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?

Hmm.. any suggestions? Are there any .Net standard methods to test things like that?


Solution

  • 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...