该数组是否存在索引?

问题描述 投票:0回答:14

我在工作中继承了一些代码,这些代码的味道非常难闻。 我希望找到最轻松的解决方案。

有没有办法检查某个任意数字是否是数组中的有效元素?

示例 - 我需要检查 array[25] 是否存在。

我更愿意在不通过数组执行 foreach() 来查找行的情况下执行此操作。

有没有办法做到这一点,或者我是否陷入了 foreach 循环?

c# arrays indexing
14个回答
171
投票

测试长度

int index = 25;
if(index < array.Length)
{
    //it exists
}

151
投票

您也可以使用 LINQ 来实现这一点:

var exists = array.ElementAtOrDefault(index) != null;

25
投票

“是有效元素”到底是什么意思?你可以这样做:

if (array.Length >= 26)

它会告诉你 25 是否是数组的有效索引(假设下限为 0)。

如果你需要知道它是否非空,只需使用:

if (array[25] != null)

(或两者的组合)。

如果这些没有帮助,请为您的问题给出“有效”的更准确含义。


13
投票

假设您还想检查该项目是否不为空

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

5
投票
// 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
}

2
投票

因为 ElementAtOrDefault() 如果不存在则返回 null,这可能会导致意想不到的后果。

我过去常常在一行中完成:

string sval = array.ElementAtOrDefault(index) ?? "" //for strings
int ival = array.ElementAtOrDefault(index) ?? 0 //for ints
. . . //etc

1
投票

您可以使用数组的长度,看看您的任意数字是否适合该范围。 例如,如果您有一个大小为 10 的数组,则 array[25] 无效,因为 25 不小于 10。


1
投票

您可以使用列表,这样您就可以检查是否存在。

List<int> l = new List<int>();
l.Add(45);
...
...

if (l.Count == 25) {
  doStuff();
}
int num = 45;
if (l.Contains(num)) {
  doMoreStuff();
}

1
投票

array.length
会告诉你数组中有多少个元素


1
投票

这里的答案很简单,但它们仅适用于一维数组。

对于多维数组,检查 null 是判断元素是否存在的直接方法。此处的示例代码检查 null。请注意,try/catch 块(可能)是多余的,但它使块防弹。

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);
}

0
投票

您可以检查索引是否小于数组的长度。 这不会检查空值或其他奇怪的情况,在这些情况下,可以为索引分配一个值,但尚未明确给出该值。


0
投票

您可以检查数组的长度,看看第 25 项在数组中是否有效,然后您可以使用

if (array.Length > 25)
{ 
   if (array[25] != null)
   {
       //good
   }
}

查看数组项本身是否已设置。


0
投票

听起来很像您正在使用数组来存储不同的字段。这绝对是代码味道。我会尽可能避免使用数组,因为它们通常不适合(或不需要)在高级代码中。

切换到简单的词典在短期内可能是一个可行的选择。就像使用一个大的财产包类一样。有很多选择。你现在遇到的问题只是糟糕设计的一个症状,你应该考虑解决根本问题,而不是仅仅修补糟糕的设计,所以目前来说,它基本上是有效的。


0
投票

我创建了一个适用于列表和大多数数组的扩展方法。 它检查:数组是否为空、索引是否有效以及元素是否为非空。

public static bool hasValueAt<T>(this IList<T> list, int index)
{
        return (list != null && list.Count > index && index >= 0 && list[index] != null);
}

它适用于下限为 0 的数组和列表。如果您想知道我为什么提到这一点,请参阅:GetLowerBound()

string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };
if (cars.hasValueAt(3)) { }

int[] ints = new int[7];
if (ints.hasValueAt(-1)) { }

var objects = new List<object[]>();
int i = 4, j = 5;
if (objects.hasValueAt(i) && objects[i].hasValueAt(j)) { }
© www.soinside.com 2019 - 2024. All rights reserved.