How to reduce multiple nested foreach blocks

前端 未结 2 1550
小蘑菇
小蘑菇 2021-01-21 07:58

I have the following scenario:

var Ids = object1.GetIds(); // returns IEnumerable
foreach (var id in Ids)
{
    foreach (var relatedObject in object1.         


        
2条回答
  •  鱼传尺愫
    2021-01-21 08:20

    Personally I like to take full advantage of the optional braces/block for foreach loops.

    You can't reduce the complexity. But you can make it look nicer

    IEnumerable Ids = object1.GetIds()
    
    foreach (var id in Ids)
    foreach (var relatedObject in object1.GetRelatedObjects(id))
    {
         DoSomething(relatedObject);
    }
    

提交回复
热议问题