将一个值与整个数组进行比较 [英] Compare one value to whole array

查看:310
本文介绍了将一个值与整个数组进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将单个值与整个数组进行比较

int IDuser = 100;

int [] IDUserkey = {94,96,98,100};

我的条件是如果IDUser不存在于IDUserkey中(假设IDUser是150),我想写一些代码..如果IDuser存在确定..

请帮助...

how to compare single value to whole array
int IDuser=100;
int [] IDUserkey={94,96,98,100};
my condition is if IDuSer not present in IDUserkey (suppose IDUser is 150) ,i want write some code..if IDuser present ok..
please help...

推荐答案

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)


这篇关于将一个值与整个数组进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆