Reputation: 9298
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
}
Upvotes: 122
Views: 155288
Reputation: 137
Inspiring by Yuriy Faktorovich's answer, I have used this. posting here incase it helps anyone in the future.
public static bool TryGetElementByIndex<T>(this List<T> list, int index, out T element)
{
var e = list.ElementAtOrDefault(index);
if (e != null)
{
element = e;
return true;
}
element = default;
return false;
}
Upvotes: 2
Reputation: 6248
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;
}
Upvotes: 0
Reputation: 2682
int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);
Upvotes: 0
Reputation: 68687
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
.
Upvotes: 296
Reputation: 126864
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
Upvotes: 13