我有一个WPF申请,在那里我有一个硬币喷泉。每隔10毫秒,就会将coin[i]添加到名为coins的list中。这些硬币生成的动画,找到硬币与此语句for (int i = 0; i < coins.Count; i++)。要删除我调用的对象:
if (coins[i].Top > 550)
{
coins.RemoveAt(i);
canvas.Children.Remove(coin[i]);
}(顶部是使用边距设置顶部位置的类的一部分)。
但是,在使用coins.RemoveAt(i);时,列表号也会被移除,因此列表号中的所有其他项都将向下移动以缩小“差距”。有什么方法可以阻止它填补“空白”,当删除项目?
发布于 2016-10-11 20:27:07
用下面的代码替换For循环。这将发现所有的硬币顶部属性> 550,然后迭代它们从硬币列表和canvas.Children收藏中删除它们。
var coinsToRemove = coins.Where(coin => coin.Top > 550);
foreach (var coin in coinsToRemove)
{
coins.Remove(coin);
canvas.Children.Remove(coin);
}发布于 2016-10-11 20:31:11
Coins.Insert(我,新硬币());是我认为将解决“填补空白”问题的额外代码行。我的解决办法是用一个空的物体来填补空白。请参阅下面的测试用例:
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
}
}
}https://stackoverflow.com/questions/39985593
复制相似问题