How to reduce multiple nested foreach blocks

前端 未结 2 1549
小蘑菇
小蘑菇 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:12

    When there is nothing between the two loops, before or after the nested one, you can use SelectMany to "flatten" two loops into one:

    foreach (var relatedObject in Ids.SelectMany(object1.GetRelatedObjects)) {
        ...
    }
    

    One major difference between this loop and the loop that you have is that id is no longer in scope. Assuming that relatedObject exposes a public Id property, this should not be a problem in your situation, because you could extract the id back with

    var id = relatedObject.Id;
    
    0 讨论(0)
  • 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<int> Ids = object1.GetIds()
    
    foreach (var id in Ids)
    foreach (var relatedObject in object1.GetRelatedObjects(id))
    {
         DoSomething(relatedObject);
    }
    
    0 讨论(0)
提交回复
热议问题