A.F*_*hry 4 c# loops if-statement
是否有更好(更简洁)的方法在if/else条件下迭代相同的集合对象,而不是以下方式:
bool condition = DetermineConditionValue();
if(condition)
{
foreach(var v in variables)
{
PerformAction(v);
}
else
{
foreach(var v in variables)
{
PerformAnotherAction(v);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来避免两次写循环?
你可以用 Action<T>
Action<YourParameterTypeHere> actionToDo = DetermineConditionValue()
? PerformAction
: PerformAnotherAction;
foreach(var v in variables)
{
actionToDo(v);
}
Run Code Online (Sandbox Code Playgroud)