簡體   English   中英

C#:測試 int x 是否是給定集合的元素的最優雅方法?

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

問題:測試是否 x ∉ { 2, 3, 61, 71 }

我經常想知道是否沒有比以下更好的方法:

if (x != 2 && x != 3 && x != 61 && x != 71)
{
  // do things
}

if (!new List<int>{ 2, 3, 61, 71 }.Contains(x))
{
  // do things
}

后一個看起來很優雅,但實際上讀起來有點煩人,尤其是因為倒置。 這有點難看,因為在英語中我們說"x is not element of ..." ,這很難在 C# 中表達而不刺激開銷。 也許有人會說if (Object(x).IsElementOf(new[] { ... }))左右?

嗯..有什么建議嗎? 是否有任何 .Net 標准方法來測試這樣的事情?

我使用擴展方法:

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

如果您喜歡此名稱,可以將其重命名為IsElementOf ...

老問題,但還沒有看到這個簡單的答案:

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

您可以使用以下 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

為了可讀性,您可以將其放在擴展方法中:

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

//usage
if(3.IsElementOf(list)) //in the list

關於什么

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

或那些線路上的東西?

結果證明 2、3、61 和 71 是質數。 因此,將您的數字模數為 25986(= 2 * 3 * 61 * 71)。 如果結果非零,則繼續執行 if 塊。

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

我強烈建議在代碼中對這種技術進行大量注釋。

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
}

它仍然與您習慣的相反,但它更具表現力(如果列表具有任何等於元素的值)。

假設您的意思是 && 而不是 ||,您可以編寫一個 func 並在整個代碼中使用它。 您可以縮短 new[] 部分,因為類型 (int) 是由 func 的 in 參數推斷出來的。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM