Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove even numbers from an arraylist in c#?

So I’m trying to remove all even numbers from the generated random list I created. But this message keeps showing up: "System.ArgumentOutOfRangeException: ‘Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index’

I don’t know what I’m doing wrong. What do I need to change?

public partial class Form2 : Form
{
    
    ArrayList array = new ArrayList();
    int count = -1;
    int[] numbers = new int[5];
    
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Random randNum = new Random();
        for (int i = 0; i < 5; i++)
        {
            
            numbers[i] = randNum.Next(-100, 100);
  
            array.Add(numbers[i]);
            richTextBox1.Clear();
            
        }
        for (int i = 0; i <= count; i++)
        {
            //displays random numbers to rich textbox
            richTextBox1.AppendText(array[i].ToString() + '\n');
            
        }
        
    }

    private void button2_Click(object sender, EventArgs e)
    {
        foreach (int i in array)
        {
            if (Convert.ToInt32(array[i]) % 2 == 0)
            {
                array.RemoveAt(i);
            }
            richTextBox1.Text = array[i].ToString();
        }
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code in Button2_click is wrong. You are using foreach loop and then trying to access the index of array using its elements value.
change your second button code with following code

        for (int i = 0; i < array.Count; )
        {
            if (Convert.ToInt32(array[i]) % 2 == 0)
            {
                array.RemoveAt(i);
            }
            else {
                i++;
            }
            
        }
        foreach (var item in array)
        {
            richTextBox1.Text = item +"\n";
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading