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

【C#】Dictionaryのキーと値のペアの数を取得する方法(Countプロパティ)

C#のDictionaryで要素数を取得するには?

C#のDictionary<TKey, TValue>に格納されているキーと値のペア(要素)の数を取得するには、Countプロパティを使用します。このプロパティは、ディクショナリ内に現在存在する要素の総数をint型で返します。

例1:Countプロパティで要素数を確認する

以下のコードでは、まず5つの要素を追加してCountを表示し、続いてContainsValueメソッドで特定の値が存在するかどうかを確認します。最後にClearメソッドですべての要素を削除し、削除後のCountがどう変化するかも確認しています。

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();

      dict.Add("One", "Chris");
      dict.Add("Two", "Steve");
      dict.Add("Three", "Messi");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");

      Console.WriteLine("Count of elements = "+dict.Count);

      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }

      if (dict.ContainsValue("Angelina"))
         Console.WriteLine("Value found!");
      else
         Console.WriteLine("Value isn't in the dictionary!");

      dict.Clear();
      Console.WriteLine("\nCleared Key/value pairs...");

      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }

      Console.WriteLine("Count of elements now = "+dict.Count);
   }
}

出力結果

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

Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value isn't in the dictionary!
Cleared Key/value pairs...
Count of elements now = 0

このように、Clear()を呼び出した後はすべてのキーと値のペアが削除され、Countが0になっていることがわかります。

例2:シンプルに要素数だけを取得する

もう少し簡単な例も見てみましょう。要素を追加した直後に、Countプロパティで要素数を表示するだけのコードです。

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      Dictionary<string, string> dict = new Dictionary<string, string>();

      dict.Add("One", "David");
      dict.Add("Two", "Brian");
      dict.Add("Three", "Paul");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");

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

出力結果

Count of elements = 5

まとめ

Dictionaryのキーと値のペアの数を取得するには、Countプロパティを使うのが基本です。要素の追加や削除に応じて自動的に更新されるため、常に現在の要素数を正確に把握できます。なお、似た名前のCapacityプロパティは内部データ構造が確保している容量を示すものであり、実際の要素数であるCountとは意味が異なる点に注意してください。

  1. Pythonの辞書で値からキーを取得する2つの方法

    Pythonの辞書(dict)は「キー」と「値」のペアでデータを管理するコレクションです。通常はキーを指定して値を取り出しますが、この記事ではその逆――値がわかっているときに、対応するキーを取得する方法を2つ紹介します。 方法1:keys()・values()・index()を組み合わせる 辞書のkeys()メソッドとvalues()メソッドでそれぞれキーと値のリストを作成し、リストのindex()メソッドで目的の値の位置を特定します。キーと値は同じ順序で並んでいるため、同じインデックスを指定すれば対応するキーが取得できます。 サンプルコード dictA = {Mon: 3, Tue: 11,

  2. Redis HLENコマンドの使い方 – ハッシュに含まれるフィールド数を取得する方法

    このチュートリアルでは、RedisのHLENコマンドを使って、指定したキーに保存されているハッシュ値に含まれるフィールドの数を取得する方法を解説します。redis-cliからHLENコマンドを実行することで、ハッシュ内のフィールド総数を簡単に確認できます。 HLENコマンドの構文 redis host:port> HLEN <キー名> 指定したキーに対してHLENコマンドを実行すると、そのハッシュに登録されているフィールドの数が返されます。 実行結果(戻り値) - (integer) ハッシュに含まれるフィールドの数 - 0:キーが存在しない場合 - エラー:キーは存在するが