Efr*_*ain 26 .net c# coding-style
问题:测试是否x∉{2,3,61,71}
我经常想知道是否有更好的方法:
if (x != 2 && x != 3 && x != 61 && x != 71)
{
// do things
}
Run Code Online (Sandbox Code Playgroud)
和
if (!new List<int>{ 2, 3, 61, 71 }.Contains(x))
{
// do things
}
Run Code Online (Sandbox Code Playgroud)
后者看起来相当优雅,但实际上如果你读它会有点恼火,特别是因为倒置.这是一种丑陋的事情,因为在英语中我们说"x不是...的元素",这在C#中难以表达而不会刺激开销.也许一个人if (Object(x).IsElementOf(new[] { ... }))
怎么说?
嗯......有什么建议吗?是否有任何.Net标准方法来测试这样的事情?
Tho*_*que 44
我使用扩展方法:
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))
...
Run Code Online (Sandbox Code Playgroud)
IsElementOf
如果您更喜欢这个名字,可以将其重命名为...
您可以使用以下LinQ方法:
var list = new List<int> { 1, 2, 3, 4, 5 };
var number = 3;
if (list.Any(item => item == number))
//number is in the list
Run Code Online (Sandbox Code Playgroud)
为了便于阅读,您可以将其放在扩展方法中:
public static bool IsElementOf(this int n, IEnumerable<int> list)
{
return list.Any(i => n == i);
}
//usage
if(3.IsElementOf(list)) //in the list
Run Code Online (Sandbox Code Playgroud)