[C#]Dictionary(辞書)のValueの最大値を取得するには?

C#

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

Dictionary(辞書)のValue(値)の最大値を取得する方法を紹介します。

スポンサーリンク

方法

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

Dictionary(辞書)のValue(値)の最大値を取得するには、ValuesとMax()を使います。

まず、System.Linqを導入します。

using System.Linq;

DictionaryのValuesプロパティにアクセスします。

そして、ValuesプロパティからMax()を呼び出します。

T maxValue = myDict.Values.Max();

上記のMax()は、ValuesにアクセスしたDictionary(辞書)のValueの最大値を返します。

使用例

using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
    public static void Main()
    {
	    Dictionary<string, int> numbers = new Dictionary<string, int>()
	    {
	        { "one", 1 },
	        { "two", 2 },
	        { "three", 3 },
	        { "ten", 10 },
	        { "four", 4 },
	        { "five", 5 },
	    };
	    
	    int maxValue = numbers.Values.Max();
	    
	    Console.WriteLine(maxValue); //10
	}
}

コメント

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