开发者

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

If I have a list of stri开发者_运维百科ngs

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
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜