【问题标题】:optimizing the if and foreach for nullchecks优化空检查的 if 和 foreach
【发布时间】:2018-10-10 03:31:59
【问题描述】:

是否要优化此代码以进行空检查?

if (objA != null && objA .Length > 0)
            {
                foreach (var child in objA )
                {
                    if (child.Any != null)
                    {
                        foreach (var a in child.Any)
                        {
                            if (a.Name.ToLower() == "code")
                            {
                                //some code
                            }
                        }
                    }
                }
            }

【问题讨论】:

  • 您可以放心地丢失objA.Length > 0,因为foreach 循环会有效地复制它。没有看到其他任何东西。
  • @glenebob:确定
  • objA的类型是什么?请向我们展示您的Any 属性的定义。
  • @mjwills: objA 是 objectA 的数组。
  • foreach (var a in objA?.SelectMany(z => z?.Any).Where(y => y?.Name?.ToLower() == "code") ?? Enumerable.Empty<YourTypeHere>()) 可能会起作用。

标签: c# asp.net .net c#-4.0


【解决方案1】:

我认为您想使用 C# 6 空条件 ? 运算符。这是一些伪代码:

for (int i = 0; i < objA?.Length; i++)
{
    ExecuteCode(objA[i]?.Any);
}    

...

static void ExecuteCode(YourTypeHere[] children)
{
    for (int i = 0; i < children?.Length; i++)
    {
        if (children[i]?.Name?.ToLower() == "code")
        {
            //some code
        }
    }
}

使用 for 循环比 foreach 更快:In .NET, which loop runs faster, 'for' or 'foreach'?。两个循环都比 Linq 稍快。

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2013-03-16
    • 2012-02-03
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多