Modifying list inside foreach loop

后端 未结 3 1420
暖寄归人
暖寄归人 2021-01-01 16:51

I have a construction similar to this (but a lot more complicated):

var list = new List();

// .. populate list ..

foreach(var item i         


        
3条回答
  •  -上瘾入骨i
    2021-01-01 17:40

    Yes, you could break, if that's what you really want. An exception won't be thrown until the for loop tries to grab the next item from the list.

    But I've found it's easiest just to create and iterate across a copy of the list so you don't have to worry about it.

    foreach(var item in list.ToList())
    

    The added performance overhead of an extra, untouched list is generally negligible compared to the maintainability costs of more complex code.

提交回复
热议问题