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)?
You can use linq for that:
foreach (var item in Neighbors.Where(n => n != null))
{
// do something
}
How about
neighbors.Where(x => x != null).ToList().ForEach(x => DoSomething(x));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With