首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#删除列表对象

问C#删除列表对象
EN

Stack Overflow用户
提问于 2016-10-11 19:52:35
回答 2查看 215关注 0票数 0

我有一个WPF申请,在那里我有一个硬币喷泉。每隔10毫秒,就会将coin[i]添加到名为coins的list中。这些硬币生成的动画,找到硬币与此语句for (int i = 0; i < coins.Count; i++)。要删除我调用的对象:

代码语言:javascript
复制
if (coins[i].Top > 550)
{
    coins.RemoveAt(i);
    canvas.Children.Remove(coin[i]);
}

(顶部是使用边距设置顶部位置的类的一部分)。

但是,在使用coins.RemoveAt(i);时,列表号也会被移除,因此列表号中的所有其他项都将向下移动以缩小“差距”。有什么方法可以阻止它填补“空白”,当删除项目?

EN

回答 2

Stack Overflow用户

发布于 2016-10-11 20:27:07

用下面的代码替换For循环。这将发现所有的硬币顶部属性> 550,然后迭代它们从硬币列表和canvas.Children收藏中删除它们。

代码语言:javascript
复制
var coinsToRemove = coins.Where(coin => coin.Top > 550);

foreach (var coin in coinsToRemove)
{
    coins.Remove(coin);
    canvas.Children.Remove(coin);
}
票数 2
EN

Stack Overflow用户

发布于 2016-10-11 20:31:11

Coins.Insert(我,新硬币());是我认为将解决“填补空白”问题的额外代码行。我的解决办法是用一个空的物体来填补空白。请参阅下面的测试用例:

代码语言:javascript
复制
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
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39985593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档