Oliver Brodersen
Oliver Brodersen

Reputation: 79

C# Removing list object

I have a WPF application where I have a coin fountain. Every 10 milliseconds a coin[i] is added to a list called coins. These coins generate with an animation that finds the coin with this for statement for (int i = 0; i < coins.Count; i++). To remove the object I call:

if (coins[i].Top > 550)
{
    coins.RemoveAt(i);
    canvas.Children.Remove(coin[i]);
}

(top is part of a class that sets the top position using margin).

However, when using the coins.RemoveAt(i); the list number gets removed as well, so all other items in the list number will be moved down to close the "gap". Is there any way to stop it from filling the "gap", when removing the item?

Upvotes: 0

Views: 237

Answers (2)

djg
djg

Reputation: 129

coins.Insert(i, new coin()); is the extra line of code I believe will solve your "filling the gap" problem. My solution is to fill the gap with an empty object. See My test case below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {
        class b 
        {
            public int i;
            public b(int x) { i = x; } //Constructor which instantiates objects with respective properties
            public b() { }             //Constructor for empty object to fill gap
        }

        static void Main(string[] args)
        {
            List<b> integers = new List<b>(); //List of objects
            integers.Add(new b(5));           //Add some items
            integers.Add(new b(6));
            integers.Add(new b(7));
            integers.Add(new b(8));

            for (int i = 0; i < integers.Count; i++)
            {
                Console.WriteLine(integers[i].i); //Do something with the items
            }

            integers.RemoveAt(1);                 //Remove the item at a specific index
            integers.Insert(1, new b());          //Fill the gap at the index of the remove with empty object
            for (int i = 0; i < integers.Count; i++)    //Do the same something with the items
            {
                Console.WriteLine(integers[i].i);       //See that The object that fills the gap is empty
            }
            Console.ReadLine();                     //Wait for user input I.E. using a debugger for test
        }
    }
}

Upvotes: 0

LittleDebugger
LittleDebugger

Reputation: 264

Replace the For loop with the code below. This will find all of the coins with a Top property > 550 then iterate over them removing them from the coins list and the canvas.Children collection.

var coinsToRemove = coins.Where(coin => coin.Top > 550);

foreach (var coin in coinsToRemove)
{
    coins.Remove(coin);
    canvas.Children.Remove(coin);
}

Upvotes: 2

Related Questions