C #-delete an element from foreach

Source: Internet
Author: User

When an element is deleted in foreach, Each deletion changes the size of the Set and the value of the element index. An exception occurs when an element is deleted in foreach.

The solution is to use a for loop and traverse from the end to the header.

For traversal from start to end, you will delete only half of the elements. As follows:

namespace CSharpLearning{    using System;    using System.Collections.Generic;    ///     /// The program.    ///     public class Program    {        ///         /// The main.        ///         public static void Main()        {            List
 
   integers = new List
  
   ();            for (int i = 0; i < 100; i++)            {                integers.Add(i);            }            for (int i = 0; i < integers.Count; i++)            {                integers.Remove(integers[i]);            }            Console.WriteLine(integers.Count);        }    }}// Output: 50
  
 

The correct method is to traverse from the end to the header, as shown below:

namespace CSharpLearning{    using System;    using System.Collections.Generic;    ///     /// The program.    ///     public class Program    {        ///         /// The main.        ///         public static void Main()        {            List
 
   integers = new List
  
   ();            for (int i = 0; i < 100; i++)            {                integers.Add(i);            }            for (int i = integers.Count - 1; i >= 0; i--)            {                integers.Remove(integers[i]);            }            Console.WriteLine(integers.Count);        }    }}// Output: 0
  
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.