检查一行 C# 中的数组元素是否不为空
Check if Array element is not null in one line C#
我得到了一个 neighbor
数组(由 Tile 对象组成),无论是否填充了所有元素,它的长度始终为 4。如果该元素/位置不为空,我想扫描该数组并更改 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?)。
是否有另一种方法来检查数组的元素是否为空,只使用一行(最好不使用 hack)?
您可以为此使用 linq:
foreach (var item in Neighbors.Where(n => n != null))
{
// do something
}
怎么样
neighbors.Where(x => x != null).ToList().ForEach(x => DoSomething(x));
如果您需要操作的 return 值,请使用 select
var result = neighbors.Where(x => x != null).Select(x => MyAction(x)).ToList();
我得到了一个 neighbor
数组(由 Tile 对象组成),无论是否填充了所有元素,它的长度始终为 4。如果该元素/位置不为空,我想扫描该数组并更改 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?)。
是否有另一种方法来检查数组的元素是否为空,只使用一行(最好不使用 hack)?
您可以为此使用 linq:
foreach (var item in Neighbors.Where(n => n != null))
{
// do something
}
怎么样
neighbors.Where(x => x != null).ToList().ForEach(x => DoSomething(x));
如果您需要操作的 return 值,请使用 select
var result = neighbors.Where(x => x != null).Select(x => MyAction(x)).ToList();