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

markzzz picture markzzz · Jan 18, 2012 · Viewed 7k times · Source

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!

Answer

Jon picture Jon · Jan 18, 2012

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.