Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Array element is not null in one line C#

I got a neighbor array (consisting of Tile objects), that always has the length of 4, regardless if all elements are filled or not. I want to scan through that array and change the color of a PB contained in the Tile if that element / position is not null. I can do this via a standard if neighbors[i] = null check using the following code:

for (int i = 0; i < Neighbors.Count(); i++)
{
    if (Neighbors[i] != null)
       Neighbors[i].TilePB.Backcolor = Color.Red;
    else
       continue; // just put that here for some more context.
}

But I was wondering if I could do this in one line, similar to using the ? operator. I've tried using a ternary operator, but I can't continue using one (ternary statement I tried: Neighbors[i] != null ? /* do something */ : continue, source to why it doesn't work: Why break cannot be used with ternary operator?).

Is there another way to check if an element of an array is null, only using one line (preferably without using a hack)?

like image 723
Sander Koldenhof Avatar asked Dec 14 '22 12:12

Sander Koldenhof


2 Answers

You can use linq for that:

foreach (var item in Neighbors.Where(n => n != null))
{
    // do something
}
like image 114
Dmytro Mukalov Avatar answered Dec 22 '22 00:12

Dmytro Mukalov


How about

neighbors.Where(x => x != null).ToList().ForEach(x => DoSomething(x));
like image 25
sellotape Avatar answered Dec 22 '22 00:12

sellotape