[ACCEPTED]-C#: Most elegant way to test if int x is element of a given set?-coding-style

Accepted answer
Score: 51

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 1 it to IsElementOf if you prefer this name...

Score: 14

Old question, but haven't seen this simple 1 answer:

!new []{2, 3, 61, 71}.Contains(x)
Score: 6

You could use following LinQ method:

var list = new List<int> { 1, 2, 3, 4, 5 };
var number = 3;

if (list.Any(item => item == number))
    //number is in the list

And 2 for the readability you can put it in an 1 extension method:

public static bool IsElementOf(this int n, IEnumerable<int> list)
{
    return list.Any(i => n == i);
}

//usage
if(3.IsElementOf(list)) //in the list
Score: 2

what about

if(new[] { 2, 3, 61, 71 }.Except(x).FirstOrDefault() != 0)
{
   ...
}

or something on those lines?

0

Score: 1

it turns out that 2, 3, 61, and 71 are prime. so, modulo 4 your number into 25986 (= 2 * 3 * 61 * 71). If 3 the result is non-zero, then continue with 2 the if block.

if ((x < 2) || (25968 % x != 0))
{ /* do all the stuff */ }

I would strongly advise heavily 1 commenting this technique in the code.

Score: 0
var list=CreateNewList(); //returns your list of elements
var element=GetElement(); //returns an element that might be in the list
if(list.Any(x=>x.Equals(element))
{
  //do something
}

It's still inverted from what you're used 2 to but it's more expressive (if the list 1 has any value that equals element).

Score: 0

Assuming you meant && and not ||, you 4 can just write a func and use that throughout 3 your code. You can shorten the new[] part 2 since the type (int) is infered by the in 1 paramter of the func.

Func<int, bool> IsSafe = x => !new[] { 2, 3, 61, 71 }.Contains(x);

Console.WriteLine(IsSafe(68)); // is true
Console.WriteLine(IsSafe(2));  // is false

More Related questions