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

C#

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

Dictionary(連想配列)の最大値を取得する方法を紹介します。

スポンサーリンク

方法

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

Dictionary(連想配列)の最大値を取得する方法は、2つあります。

Value(値)の最大値を取得する

1つは、Value(値)の最大値を取得する方法です。

まず、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
	}
}

Key(キー)の最大値を取得する

もう1つは、Key(キー)の最大値を取得する方法です。

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

using System.Linq;

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

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

T maxKey = myDict.Keys.Max();

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

使用例

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

まとめ

Dictionary(連想配列)の最大値を取得する方法は、次の2つです。

  • Valueの最大値を取得する方法
    T maxValue = myDict.Values.Max();
  • Keyの最大値を取得する方法
    T maxKey = myDict.Keys.Max();

コメント

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