What is the best way to modify a list in a 'foreach' loop?

前端 未结 11 750
不思量自难忘°
不思量自难忘° 2020-11-22 05:23

A new feature in C# / .NET 4.0 is that you can change your enumerable in a foreach without getting the exception. See Paul Jackson\'s blog entry An Interest

11条回答
  •  -上瘾入骨i
    2020-11-22 06:06

    To add to Timo's answer LINQ can be used like this as well:

    items = items.Select(i => {
    
         ...
         //perform some logic adding / updating.
    
         return i / return new Item();
         ...
    
         //To remove an item simply have logic to return null.
    
         //Then attach the Where to filter out nulls
    
         return null;
         ...
    
    
    }).Where(i => i != null);
    

提交回复
热议问题