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

Time:03-20

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();
        }
    }

CodePudding user response:

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";
        }

CodePudding user response:

In your second for loop of button1_click(), you are travering till count variable whose value is -1. How can you traverse from 0 to -1 in increment fashion ?

CodePudding user response:

You should change your enumeration like:

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

CodePudding user response:

Using LINQ you can achieve this easily.

var oddArray = array.Where(a => a % 2 != 0);
richTextBox1.Text = string.Join(", ", oddArray);

PS - You just need to add a namespace i.e. System.Linq

  • Related