Check if an item exists at position [x] in the list

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, the position of index 2 contains an element, is there an easy way to do this without considering the length of the list or using try catch?

Since this fails, I can get around it with try catch, but it seems excessive

 if(list.ElementAt(2) != null) { // logic } 
+44
list c #
Oct. 16 2018-10-16
source share
3 answers
 if(list.ElementAtOrDefault(2) != null) { // logic } 

ElementAtOrDefault () is part of the System.Linq namespace.

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

+122
Oct 16 2018-10-10
source share
 if (list.Count > desiredIndex && list[desiredIndex] != null) { // logic } 
+4
Oct. 16 2018-10-16
source share
 int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null); 
0
Sep 19 '17 at 21:57
source share



All Articles