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
}
怎么样
neighbors.Where(x => x != null).ToList().ForEach(x => DoSomething(x));
如果您需要动作的返回值,请使用select
var result = neighbors.Where(x => x != null).Select(x => MyAction(x)).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.