重构循环 C#

问题描述 投票:0回答:1

重构以下代码

if (res != null)
{
    foreach ( item in List)
    {
        if (item != null)
        {
            foreach (name in nameList)
            {
                if (name.Equals("pretty"))
                {
                    DoSomething();
                }

                if (name != null)
                {

                    foreach (age in ageList)
                    {
                        DoSomething();
                    }
                }
            }
        }
    }
} 

我需要重构上面的循环以降低认知复杂度,但我无法找到替换嵌套条件的好方法。有没有办法减少嵌套?

c# loops refactoring
1个回答
0
投票

您可以反转空检查:

foreach ( item in List)
{
      if (item == null) continue;

或者使用 LINQ 进行空检查:

foreach ( item in List.Where(i => i != null))
© www.soinside.com 2019 - 2024. All rights reserved.