更新时间:2023-01-21 11:52:51
int IDuser = 100;
int[] IDUserkey = { 94, 96, 98, 100 };
if (! IDUserkey.Contains(IDuser))
{
// ID User is not present
// your code here.....
}
else
{
// ID User is present
}
注意:使用系统添加此命名空间
using System.Linq;
Cheeck
Cheeck
bool result = IDUserkey.Contains( IDuser);
如果您知道数组已排序,您可以使用:
bool exists = Array.BinarySearch( array_1,variable_1)> = 0;
那将是O(log n)ra比O(n)(所有其他都是),但它确实需要先排序数组。
就我个人而言,我通常选择第一种形式 - 假设您使用的是.NET 3.5或更高版本。
如果您需要检查多个项目并且数组很大,您可能需要创建一个HashSet< int>
HashSet< int> hashSet = new HashSet< int>(array_1);
bool exists = hashSet.Contains(variable_1)
If you know that the array is sorted, you can use:
bool exists = Array.BinarySearch(array_1, variable_1) >= 0;
That will be O(log n) rather than O(n) (which all the others are), but it does require the array to be sorted first.
Personally I normally go with the very first form - assuming you are using .NET 3.5 or higher.
If you need to check for several items and the array is large, you may want to create a HashSet <int>
HashSet <int> hashSet = new HashSet <int>(array_1);
bool exists = hashSet.Contains(variable_1)