c# check if list contains an existing element (not null)

13,374

Solution 1

Use the linq Any method:

if (myList.Any(i => i != null))
{
    DoSomeThing();
}

Solution 2

If you aren't fussed about checking a specific index of the list not being null and just want to check there is something in the list you could use this.

if(myList != null && myList.Any())
{ 
   DoSomething();
}
Share:
13,374
Mc Midas
Author by

Mc Midas

Updated on July 14, 2022

Comments

  • Mc Midas
    Mc Midas almost 2 years

    Is there some equivalent to myTestList.Count that will only count not-nullable fields?

    For example I want to do certain things when I know that between some null elements is one existing element.

    This is the behaviour I want, but can this be achieved also with pre-existing functions?

    if(myList.Count > 0){
        for(int i = 0; i < myList.Count; i++){
            if(myList[i] != null){
                DoSomething();
                break;
            }
        }
    }
    
    • gilliduck
      gilliduck about 6 years
      So you have myList[0] = null, myList[1] = something, myList[2] = null? How do you have a not null in between nulls or did I completely misread this?
    • Mc Midas
      Mc Midas about 6 years
      err yes the thing is in unity you can assign elements to fields in the inspector that come after a null element.
  • Thameem
    Thameem about 4 years
    what if a list is null.. will i get object not set to a reference... ?
  • David Arno
    David Arno about 4 years
    @Thameem, you will. In that case, use something like if (myList != null && myList.Any(i => i != null)))