2011-07-12 1 views
0

Move-UpMove-Downの項目をサポートするビルトインオーダードコレクションはありますか?MovedownとMoveDownを指定したOrderedCollection

私はその後、私はこのような何かを行うことができるようにしたい、私はアイテムを挿入するとき、それはコレクションの最後に挿入

になることを確認することができますコレクション(一覧することができる)注文したたい

Col.MoveUp(Item1);//Takes Item1 and move its index one step up. 
        //if its index is 3 it will be 2 and item on index 2 will be 3 
Col.MoveDown(item2); 
+0

あなたはその隣人と位置を交換することを意味しますか? –

+0

私は質問 – Stacker

+0

を更新しました。単にアイテムを交換することができます。 –

答えて

3

自分で作成するのはとても簡単です。ここで私はそれらを拡張メソッドとして作った。別のオプションは、独自のコレクションを定義し、Listから継承し、そこにこれらのメソッドを挿入することです。

public static class ListExtensions 
{ 
    public static void MoveUp<T>(this List<T> list, T item) 
    { 
     int index = list.IndexOf(item); 

     if (index == -1) 
     { 
      // item is not in the list 
      throw new ArgumentOutOfRangeException("item"); 
     } 

     if (index == 0) 
     { 
      // item is on top 
      return; 
     } 

     list.Swap(index, index - 1); 
    } 

    public static void MoveDown<T>(this List<T> list, T item) 
    { 
     int index = list.IndexOf(item); 

     if (index == -1) 
     { 
      // item is not in the list 
      throw new ArgumentOutOfRangeException("item"); 
     } 

     if (index == list.Count - 1) 
     { 
      // item is no bottom 
      return; 
     } 

     list.Swap(index, index + 1); 
    } 

    private static void Swap<T>(this List<T> list, int i1, int i2) 
    { 
     T temp = list[i1]; 
     list[i1] = list[i2]; 
     list[i2] = temp; 
    } 
} 
+1

スワッピングは、アイテムのインデックスよりも大きいインデックスを持つすべてのアイテムを再割り当てするため、削除と挿入の操作よりも速いと思います。 –

+0

@Miroprocessor、良い観測、ありがとう。私は投稿を更新しました。 – Andrei

0

私は考慮に境界例を取って、同じことが簡単なスワッピングによって行うことができる場合は特に、このように組み込まれて何もないと思います。

既存のコレクションの1つを拡張する独自のコレクションを実装して、目的のメソッドを追加することができます。

1

通常、並べ替えられたコレクションには「Ordered」という接頭辞が使用されますが、その必要はありません。

あなたがList<>標準と数行のコードを使用することができます:私はこれはインデックス1
にインデックス2からアイテムを移動します

//untested 
// Extension method, place in public static class. 
public static void MoveDown(this IList<T> list, int index) 
{ 
    if (index >= list.Count) ... // error 
    if (index > 0) 
    { 
     var temp = list[index]; 
     list.RemoveAt(index); 
     list.Insert(index - 1, temp); 
    } 
} 

をそして

var data = new List<string>(); 
... 
data.MoveDown(2); 

のようにそれを使用しますちょうど私が上/下の逆の概念を使用したことを認識した、それは選択肢です。

関連する問題