Foreach loop, determine which is the last iteration of the loop

前端 未结 26 961
迷失自我
迷失自我 2020-11-28 02:56

I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:

 foreach (Item result in Mod         


        
26条回答
  •  一个人的身影
    2020-11-28 03:05

    To do something additional to each element except for the last one, function based approach can be used.

    delegate void DInner ();
    
    ....
        Dinner inner=delegate 
        { 
            inner=delegate 
            { 
                // do something additional
            } 
        }
        foreach (DataGridViewRow dgr in product_list.Rows)
        {
            inner()
            //do something
        }
    }
    

    This approach has apparent drawbacks: less code clarity for more complex cases. Calling delegates might be not very effective. Troubleshooting might be not quite easy. The bright side - coding is fun!

    Having said that, I would suggest using plain for loops in trivial cases, if you know that your collection's count is not terribly slow.

提交回复
热议问题