简体   繁体   中英

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

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

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

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 ie System.Linq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM