c# - How to remove elements from a generic list while iterating over it? -


I better pattern to work with a list Looking for the elements of which each process is processed and then removed from the list based on the result

You can not use . > Remove inside foreach (Miscellaneous Elements) (because it was the result in the collection; the calculation process may not be executed. exception) ... for you (int i = 0; i & lt; Elements. Count.); I ++) and . Remove (i) because it disrupts your current status in the collection related to i .

Is there a great way to do this?

Reverse your list with the loop:

 for  (Int i = secure padding list calculation - 1; i> = 0; i--) {// some code // secure pending list. Outgoing (i); }  

Example:

  var list = new list & lt; Int & gt; (Enumerable.Range (1, 10)); (Int i = list.Count - 1; i> = 0; i--) {if (list [i]> 5) list.RemoveAt (i); } List.ForEach (i => console. WriteLine (i));  

Alternatively, you can use it to test against a WordTech:

  safePendingList.RemoveAll (item = & gt; Item.Value == someValue);  

Here's a simple example to display:

  var list = new list & lt; Int & gt; (Enumerable.Range (1, 10)); Console.WriteLine ("Before that:"); List.ForEach (i => Console.WrightLine (i)); List Remove all (I => i> 5); Console.WriteLine ("After:"); List.ForEach (i => Console.WrightLine (i));  

Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -