我在工作中接手了一些代码,其中有很臭的味道。 我希望找到最轻松的解决方案。
是否有一种方法可以检查任意数字是否是数组中的有效元素?
例如-我需要检查array [25]是否存在。
最好不要通过foreach()遍历数组来查找行来实现这一点。
有没有一种方法可以做到这一点,或者我只能使用foreach循环?
我在工作中接手了一些代码,其中有很臭的味道。 我希望找到最轻松的解决方案。
是否有一种方法可以检查任意数字是否是数组中的有效元素?
例如-我需要检查array [25]是否存在。
最好不要通过foreach()遍历数组来查找行来实现这一点。
有没有一种方法可以做到这一点,或者我只能使用foreach循环?
测试长度
int index = 25;
if(index < array.Length)
{
//it exists
}
var exists = array.ElementAtOrDefault(index) != null;
new object[]{ null }.ElementAtOrDefault(index)
将返回null
,因为索引为0的元素是 null
。使用ElementAtOrDefault
不是检查数组索引存在的好方法,添加到末尾的相等性检查会使结果不确定。 - Chris Marisicarray.Length > index
。 - Shimmy Weitzhandler"is a valid element" 是什么意思?你可以这样做:
if (array.Length >= 26)
如果您需要知道25是否为数组的有效索引(假设下限为0),可以使用以下代码:
if (array.Length > 25)
{
// valid index
}
else
{
// invalid index
}
如果您只需要知道它是否非空,只需使用以下代码:
if (array[25] != null)
(或者两者的组合)。
如果这些不能帮助您,请为您的问题给出更精确的“有效”含义。
数组索引超出了范围
。 - Muhammad Raheelif (array.Length > 25 && array[25] != null)
{
//it exists
}
if (array.Length > 25 && array[25] != null)
中必须使用&&
,如果使用单个&
将会抛出IndexOutOfRange异常。 MSDN。 - checksum// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:
int index = 25;
if (index >= 0 && index < array.Length)
{
// Array element found
}
由于ElementAtOrDefault()方法如果不存在会返回null,这可能会导致意外后果。
我通常在一行中执行以下操作:
string sval = array.ElementAtOrDefault(index) ?? "" //for strings
int ival = array.ElementAtOrDefault(index) ?? 0 //for ints
. . . //etc
public ItemContext GetThisElement(int row,
int col)
{
ItemContext ctx = null;
if (rgItemCtx[row, col] != null)
{
try
{
ctx = rgItemCtx[row, col];
}
catch (SystemException sex)
{
ctx = null;
// Perhaps do something with sex properties
}
}
return (ctx);
}
List<int> l = new List<int>();
l.Add(45);
...
...
if (l.Count == 25) {
doStuff();
}
int num = 45;
if (l.Contains(num)) {
doMoreStuff();
}
您可以使用数组的长度,看看您的任意数字是否适合该范围。例如,如果您有一个大小为10的数组,则array[25]无效,因为25不小于10。
array.length
会告诉你数组中有多少个元素