检查列表中位置[ x ]处的元素是否存在

如果我有一个字符串列表

List<String> list = new list<String>();
list.add("str1");
list.add("str2");
list.add("str3");

我想知道例如索引位置2是否包含一个元素,有没有一种简单的方法不用计算列表的长度或者使用 try catch?

由于这将失败,我可以通过一个 try catch 绕过它,但这似乎有些过分

if(list.ElementAt(2) != null)
{
// logic
}
129694 次浏览
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 (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

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;
}

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;
}