Best way to remove items from a collection

前端 未结 15 2052
天命终不由人
天命终不由人 2020-12-08 05:47

What is the best way to approach removing items from a collection in C#, once the item is known, but not it\'s index. This is one way to do it, but it seems inelegant at be

15条回答
  •  生来不讨喜
    2020-12-08 06:49

    Here is a pretty good way to do it

    http://support.microsoft.com/kb/555972

            System.Collections.ArrayList arr = new System.Collections.ArrayList();
            arr.Add("1");
            arr.Add("2");
            arr.Add("3");
    
            /*This throws an exception
            foreach (string s in arr)
            {
                arr.Remove(s);
            }
            */
    
            //where as this works correctly
            Console.WriteLine(arr.Count);
            foreach (string s in new System.Collections.ArrayList(arr)) 
            {
                arr.Remove(s);
            }
            Console.WriteLine(arr.Count);
            Console.ReadKey();
    

提交回复
热议问题