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

【C#】SortedDictionary.Add()メソッドの使い方をサンプルコード付きで解説

C#のSortedDictionary.Add()メソッドは、指定したキーと値を持つ要素をSortedDictionary<TKey, TValue>に追加するために使用されるメソッドです。この記事では、Add()メソッドの基本構文から、実際のサンプルコードとその実行結果までをわかりやすく解説します。

構文(Syntax)

Add()メソッドの構文は以下のとおりです。

public void Add (TKey key, TValue val);

各パラメータの意味は次のとおりです。

  • key:追加する要素のキー
  • val:追加する要素の値

発生する可能性のある例外

  • ArgumentNullException:keyがnullの場合にスローされます。
  • ArgumentException:同じキーの要素がすでに存在する場合にスローされます。

使用例1:int型のキーを使った場合

まずは、int型のキーとstring型の値を持つSortedDictionaryに要素を追加する例を見てみましょう。

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
   }
}

実行結果

上記のコードを実行すると、次のような出力が得られます。

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

このように、要素を追加した順序にかかわらず、SortedDictionaryは常にキー順にソートされた状態を保ちます。

使用例2:string型のキーとContainsKey()の組み合わせ

次に、string型のキーを使用した例です。あわせてContainsKey()メソッドを使い、特定のキーが存在するかどうかを確認しています。

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<string, string> sortedDict = new SortedDictionary<string, string>();
      sortedDict.Add("A", "John");
      sortedDict.Add("B", "Andy");
      sortedDict.Add("C", "Tim");
      sortedDict.Add("D", "Ryan");
      sortedDict.Add("E", "Kevin");
      sortedDict.Add("F", "Katie");
      sortedDict.Add("G", "Brad");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("\nThe SortedDictionary has the key F? = "+sortedDict.ContainsKey("F"));
   }
}

実行結果

上記のコードを実行すると、次のような出力が得られます。

SortedDictionary key-value pairs...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad
The SortedDictionary has the key F? = True

まとめ

SortedDictionary.Add()メソッドを使えば、キーと値のペアを簡単にコレクションへ追加できます。追加された要素は自動的にキー順でソートされるため、順序付きの辞書が必要な場面で非常に便利です。ただし、同じキーを再度追加しようとするとArgumentExceptionが発生するため、事前にContainsKey()メソッドでキーの存在を確認しておくと安全です。

  1. Node.jsのcrypto.generateKeyPair()メソッドで非対称鍵ペアを生成する方法

    crypto.generateKeyPair()メソッドは、指定した種類の新しい非対称鍵ペア(公開鍵と秘密鍵のペア)を生成するために使用されます。鍵ペアの生成に対応しているタイプは、RSA、DSA、EC、Ed25519、Ed448、X25519、X448、DHです。publicKeyEncodingまたはprivateKeyEncodingが指定された場合、この関数は結果に対してkeyObject.export()を呼び出した場合と同じように動作し、エンコードされた鍵データを返します。指定されていない場合は、keyObjectの該当する部分がそのまま返されます。 構文 crypto.gene

  2. HTML DOMのinsertBefore()メソッドの使い方を徹底解説

    insertBefore()メソッドとはHTML DOMのinsertBefore()メソッドは、すでに存在する子ノードの直前に、新しいノードを挿入するためのメソッドです。リストの先頭に項目を追加したい場合など、DOM操作で要素の挿入位置を細かく制御したいときに非常に便利です。構文insertBefore()メソッドの基本的な構文は以下の通りです。node.insertBefore(newNode, existingNode)パラメータこのメソッドには、以下の2つのパラメータを指定します。パラメータ説明newNode先頭に追加したい、新しく作成した子ノードですexistingNodeすでに存在