tags:

views:

49

answers:

2

Hello,

if i have a list of strings

List<String> list = new list<String>();
list.add("str1");
list.add("str2");
list.add("str3");

and I want to know if for example index position 2 contains an element, is there a simple way of doing this without counting the length of the list or using a try catch ?

as this will fail, i can get round it with a try catch, but this seems excessive

if(list.ElementAt(2) != null)
{
   // logic
}

thanks

Truegilly

+1  A: 
if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

Although you have a List, so you can use list.Count > 2.

Yuriy Faktorovich
+1  A: 
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
    // logic
}
Anthony Pegram