C#のOrderedDictionaryから指定したインデックスのエントリを削除する方法
C#のOrderedDictionaryから、指定したインデックス位置にあるエントリを削除するには、RemoveAt()メソッドを使用します。このメソッドは、引数として渡されたインデックスに対応するキーと値のペアをコレクションから取り除きます。
以下に、実際のコード例と実行結果を示します。
サンプルコード
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Books");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary elements...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.RemoveAt(4);
Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
}
}この例では、6つの要素を持つOrderedDictionaryを作成し、インデックス「4」の位置にある要素(E Clothing)をRemoveAt(4)によって削除しています。
実行結果
OrderedDictionary elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of elements in OrderedDictionary = 6 Count of elements in OrderedDictionary (Updated)= 5
実行結果から、削除前は要素数が「6」だったのに対し、RemoveAt(4)を実行した後は「5」に減っていることが確認できます。インデックスは0から始まるため、インデックス4は5番目の要素を指す点に注意してください。
別のサンプルコード
続いて、複数の要素を連続して削除する例を見てみましょう。
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("1", "AB");
dict.Add("2", "CD");
dict.Add("3", "MN");
dict.Add("4", "PQ");
Console.WriteLine("OrderedDictionary elements...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.RemoveAt(1);
dict.RemoveAt(2);
Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
}
}この例では、まずRemoveAt(1)でインデックス1の要素(2 CD)を削除します。その後、残りの要素が前に詰められるため、次のRemoveAt(2)ではインデックス2の位置にある要素(4 PQ)が削除されます。
実行結果
OrderedDictionary elements... 1 AB 2 CD 3 MN 4 PQ Count of elements in OrderedDictionary = 4 Count of elements in OrderedDictionary (Updated)= 2
このように、要素を削除すると残りの要素のインデックスが自動的に繰り上がるため、連続してRemoveAt()を呼び出す場合は、その都度インデックスが変化することに注意が必要です。
-
C#のOrderedDictionaryからすべての要素を削除する方法
C#のOrderedDictionaryからすべての要素をまとめて削除するには、Clear()メソッドを使用します。Clear()メソッドを呼び出すと、コレクションに格納されたすべてのキーと値のペアが削除され、Countプロパティの値は0に更新されます。なお、Clear()メソッドの計算量はO(n)(nは要素数)です。 例 using System; using System.Collections; using System.Collections.Specialized; public class Demo { public static void Main(){ O
-
Python Pandas入門:CategoricalIndexから指定したカテゴリを削除する方法
CategoricalIndexから特定のカテゴリを削除するには、Pandasのremove_categories()メソッドを使用します。このメソッドを使うと、指定したカテゴリがインデックスから取り除かれ、それらのカテゴリに属していた値は自動的にNaN(欠損値)に置き換えられます。必要なライブラリのインポートまず、必要なライブラリをインポートします。import pandas as pdCategoricalIndexの作成「categories」パラメータを使用してカテゴリカルデータのカテゴリを設定し、「ordered」パラメータを使用して順序付きのカテゴリカルとして扱います。catInd