Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value in a List exist (before get out of range)

Tags:

c#

list

next

I have this list :

IList<Modulo> moduli = (from Modulo module in Moduli
                       select module).ToList();

and I cycle it with for (notice i=i+2) :

for(int i=0; i<moduli.Count; i=i+2)
{
}

now, I have to check if moduli[i+1] exist (so, the next element), else I'll get a System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection..

How can I check it? Tried with :

if(moduli[i+1] != null) 
{
}

but it doesnt works!

like image 565
markzzz Avatar asked Jan 18 '12 16:01

markzzz


People also ask

How do you check for an outside array?

Another way of checking if an array is out of bounds is to make a function. This will check if the index is "in bounds". If the index is below zero or over the array length you will get the result false.

What is index out of range error?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

Which of the following is raised when an index of a sequence is out of range?

Exception IndexError Raised when a sequence subscript is out of range.

How do you check if an array contains an index C#?

IndexOf() Function in C# The C# Array. IndexOf(array, element) function gets the index of the element element inside the array array . It returns -1 if the element is not present in the array.


1 Answers

Check it the same way as you check your loop condition:

if(i + 1 < moduli.Count) // it exists

Note the < instead of <=, which is a mistake in your original code.

like image 81
Jon Avatar answered Nov 02 '22 23:11

Jon