简体   繁体   中英

Does Index of Array Exist

I've inherited some code at work that has a really bad smell. I'm hoping to find the most painless solution possible.

Is there a way to check if some arbitrary number is a valid element in an array?

Example - I need to check if array[25] exists.

Preferably I would prefer to do this without doing a foreach() through the array to found the rows.

Is there any way to do this, or am I stuck with foreach loop?

Test the length

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

您也可以使用 LINQ 来实现:

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

What exactly do you mean by "is a valid element"? You could just do:

if (array.Length >= 26)

which would tell you whether 25 is a valid index into the array or not (assuming a 0 lower bound).

If you need to know whether it's non-null or not, just use:

if (array[25] != null)

(or a combination of the two).

If these don't help, please give a more precise meaning of "valid" for your problem.

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}
// 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
}

The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

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

You can use the length of the array, and see if your arbitrary number fits in that range. For example, if you have an array of size 10, then array[25] isn't valid because 25 is not less than 10.

You can rather use a List, so you can check the existence.

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

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

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

Because ElementAtOrDefault() will return null if does not exists, this could lead to unintended consequences.

I use to do in a single line:

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

You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.

You can check the length of the array to see if item 25 is valid in the sense of being in the array, then you could use

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

to see if the array item itself has been set.

It sounds very much like you're using an array to store different fields. This is definitely a code smell. I'd avoid using arrays as much as possible as they're generally not suitable (or needed) in high-level code.

Switching to a simple Dictionary may be a workable option in the short term. As would using a big property bag class. There are lots of options. The problem you have now is just a symptom of bad design, you should look at fixing the underlying problem rather than just patching the bad design so it kinda, sorta mostly works, for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM