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 }
Contains(T) Method is used to check whether an element is in the List<T> or not.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With