Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element at position [x] exists in the list

Tags:

c#

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 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 } 
like image 463
JGilmartin Avatar asked Oct 16 '10 13:10

JGilmartin


People also ask

How do you check if an element is present in a list C#?

Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you find the location of an item in a list Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.

How do I check if a list index is valid?

An index of a list is valid only if that index can be accessed from the list, without causing some error. Generally, this means that the index must be a whole number, and it must be less than the length of the list, because any index greater than the list length is out of range.


1 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.

like image 111
Yuriy Faktorovich Avatar answered Oct 08 '22 01:10

Yuriy Faktorovich