Alex Rivera | Logout

Does an index of this array exist?

Asked 2009-04-27T18:43:49.570
117

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 find the rows.

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

Edit
Report

1 Answer

1

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();
}
answered 2009-04-27T18:45:48.910

Your Answer