C#
 Computer >> コンピューター >  >> プログラミング >> C#

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(){
      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.Clear();

      Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
   }
}

出力

上記のプログラムを実行すると、次の出力が得られます −

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)= 0

続いて、別の例を見てみましょう −

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");

      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.Clear();

      Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
   }
}

出力

上記のプログラムを実行すると、次の出力が得られます −

OrderedDictionary elements...
1 AB
2 CD
Count of elements in OrderedDictionary = 2
Count of elements in OrderedDictionary (Updated)= 0

  1. JavaScriptでキューから要素を削除する方法(dequeueの実装)

    キューから要素をデキュー(dequeue)するととは、キューの先頭(ヘッド)から要素を取り除くことを意味します。本記事では、コンテナ配列の先頭をキューのヘッドとして扱い、すべての操作をこれを基準に行います。dequeue関数の実装キューの先頭から要素を取り出すpop処理は、以下のように実装できます。dequeue() { // キューが空かどうかをチェック if (this.isEmpty()) { console.log(Queue Underflow!); return; } return this.container.shi

  2. JavaでArrayListのすべての要素を削除する方法(clearメソッドの使い方)

    JavaのArrayListからすべての要素を一括で削除したい場合は、clear()メソッドを使用します。この記事では、実際のコード例を通じて、ArrayListの全要素を削除する手順をわかりやすく解説します。1. 要素を持つArrayListを作成するまず、複数の要素を格納したArrayListを用意しましょう。以下の例では、Integer型のArrayListに7つの数値を追加しています。ArrayList<Integer> arrlist = new ArrayList<Integer>(5); arrlist.add(25); arrlist.add(50);