[C#]Dictionaryが空かどうか判定するには?

C#

どうも、ちょげ(@chogetarou)です。

Dictionaryが空かどうか判定する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Dictionaryが空かどうか判定するには、Countを使います。

具体的には、==の左辺にDictionaryのCount、右辺に0を指定します。

myDict.Count == 0

上記の==は、Dictionaryが空ならばTrue、空でなければFalseを返します。

Countは、Dictionaryの要素数を取得します。

使用例

using System;
using System.Collections.Generic;
public class Example
{
    public static void Main()
    {
        Dictionary<string, int> empty = new Dictionary<string, int>();
        
        Dictionary<string, int> numbers = new Dictionary<string, int>()
	    {
	        { "one", 1 },
	        { "two", 2 },
	        { "three", 3 },
	        { "four", 4 },
	        { "five", 5 },
	    };
	    
	    
	    if (empty.Count == 0)
	    {
	        Console.WriteLine("emptyは空です");
	    }
	    else 
	    {
	        Console.WriteLine("emptyは空ではありません");
	    }
	    
	    if (numbers.Count == 0)
	    {
	        Console.WriteLine("numberは空です");
	    }
	    else 
	    {
	        Console.WriteLine("numbersは空ではありません");
	    }
    }
}
/*
    出力:
    emptyは空です
    numberは空ではありません
*/

コメント

タイトルとURLをコピーしました