我得到了一个neighbor
数组(由Tile对象组成),总长度为4,无论是否所有元素都被填充。如果该元素/位置不为null,我想扫描该数组并更改Tile中包含的PB的颜色。我可以使用以下代码通过标准if neighbors[i] = null
检查来完成此操作:
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.
}
但我想知道我是否可以在一行中做到这一点,类似于使用?运营商。我尝试过使用三元运算符,但我不能使用continue
(我试过的三元语句:Neighbors[i] != null ? /* do something */ : continue
,源代码为什么它不起作用:Why break cannot be used with ternary operator?)。
有没有另一种方法来检查数组的元素是否为空,只使用一行(最好不使用黑客)?
您可以使用linq:
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();