JGilmartin
JGilmartin

Reputation: 9298

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

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

Answers (5)

classicSchmosby98
classicSchmosby98

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

Suamere
Suamere

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

InGeek
InGeek

Reputation: 2682

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

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

Anthony Pegram
Anthony Pegram

Reputation: 126864

if (list.Count > desiredIndex && list[desiredIndex] != null)
{
    // logic
}

Upvotes: 13

Related Questions