Check if element at position [x] exists in the list
C#ListC# Problem Overview
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
}
C# Solutions
Solution 1 - C#
if(list.ElementAtOrDefault(2) != null)
{
// logic
}
ElementAtOrDefault() is part of the System.Linq
namespace.
Although you have a Listlist.Count > 2
.
Solution 2 - C#
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
Solution 3 - C#
int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);
Solution 4 - C#
The issue the OP is trying to get at is that Count()
will have to use the enumerator to MoveNext()
through the whole IEnumerator
collection. The benefit of IEnumerable is that we should be able to stop enumerating when we reach some predicate of known information.
The problem I pointed out with the other answers is that null
is a valid value in any collection. So checking if GetElementAt...()
is null
isn't reliable.
I have a different implementation and requirement, but I changed it to add an answer for this specific question:
public bool TryElementAtOrDefault<T>(IEnumerable<T> source, int index, out T value)
{
value = default;
if (index < 0 || source == null || source.Any() == false) return false;
if (source is IList<T> list && index < list.Count)
{
value = list[index];
return true;
}
using (var e = source.GetEnumerator())
{
while (e.MoveNext())
{
if (index == 0)
{
value = e.Current;
return true;
}
index--;
}
}
return false;
}