2017-09-05 108 views
-3

以下是代码片段。我想摆脱多个foreach和null检查。我如何重构代码具有多个null检查嵌套的foreach C#

请问您可以在C#中重构它吗?

foreach (var a in aa) 
{ 
    if (a.bb != null) 
    { 
     foreach (var b in a.bb) 
     { 
      if (b.cc != null) 
      { 
       foreach (var c in b.cc) 
       { 
        //perform something 
       } 
      } 
     } 
    } 
} 
+0

任何人都可以提供可读的解决方案。 –

+1

您明确使用的标签指出,您不应将该网站用于代码审查。使用https://codereview.stackexchange.com/ - 虽然我仍然认为这个问题是不够的。 –

+0

[mcve]会很好 - 我希望能够复制,粘贴和运行您的代码。 – Enigmativity

回答

0

如何:

aa.ForEachIfNotNull(
    a => a.bb.ForEachIfNotNull(
     b => b.cc.ForEachIfNotNull(
      c => { /* perform something */ }))); 

你只需要此扩展方法:

public static class NullListEx 
{ 
    public static void ForEachIfNotNull<T>(this IEnumerable<T> source, Action<T> action) 
    { 
     if (source != null) 
     { 
      foreach (var t in source) 
      { 
       action(t); 
      } 
     } 
    } 
} 
0

您可以使用LINQ,但我不认为这是一个进步:

aa.Where(a => a.bb != null).ToList().ForEach(a => a.bb.Where(b => b.cc != null).ToList().ForEach(c => { /* do something */ })); 

你也可以通过使用n来避免测试ULL合并运算符:

foreach (var a in aa) { 
    foreach (var b in a.bb ?? Enumerable.Empty<bType>()) { 
     foreach (var c in b.cc ?? Enumerable.Empty<cType>()) { 
      //perform something 
     } 
    } 
} 

因为我不知道该类型我只是把bTypecTypea.bba.bb.cc元素。