2016-10-11 3 views
0

私はコインの噴水を持っているWPFアプリケーションを持っています。 10ミリ秒ごとにと呼ばれるlistcoin[i]が追加されます。これらのコインは、for (int i = 0; i < coins.Count; i++)のステートメントでコインを見つけるアニメーションで生成されます。C#リストオブジェクトの削除

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

(はマージンを使用して、トップの位置を設定し、クラスの一部であるトップ):私が呼び出すオブジェクトを削除します。

しかし、coins.RemoveAt(i);を使用すると、リスト番号も削除されるので、リスト番号の他のすべての項目は下に移動して「ギャップ」を閉じます。アイテムを取り除くときに「ギャップ」を埋めるのを止める方法はありますか?

+1

そして配列。そして、私はキャンバスになるでしょう。子供たち。最初に離れてください。 – Paparazzi

+0

これは、パパラッチが言っているように、私はcanvas.Children.Remove(コイン[私])を最初に呼び出すことになると思います。 – DForck42

+0

forループ開始インデックスは、リストの最大値で指定します。その後、ループをカウントダウンします。その後、インデックスを削除することができます。インデックスを削除すると問題ありません。 – deathismyfriend

答えて

2

Forループを以下のコードに置き換えます。これにより、すべてのコインがTopプロパティ> 550で検索され、コインリストとキャンバスからそれらを削除します.Childrenコレクション。

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

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

coins.Insert(i、new coin());私はあなたの "ギャップを埋める"問題を解決すると信じているコードの余分な行です。私の解決策は、ギャップを空のオブジェクトで埋めることです。 以下のテストケースを参照してください。

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 
     } 
    } 
} 
関連する問題