[ACCEPTED]-C#: Most elegant way to test if int x is element of a given set?-coding-style
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...
Old question, but haven't seen this simple 1 answer:
!new []{2, 3, 61, 71}.Contains(x)
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
what about
if(new[] { 2, 3, 61, 71 }.Except(x).FirstOrDefault() != 0)
{
...
}
or something on those lines?
0
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.
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).
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.