どうも、ちょげ(@chogetarou)です。
Dictionary(辞書)のValue(値)の最大値のKey(キー)をする方法を紹介します。
方法

Dictionary(辞書)のValue(値)の最大値のKey(キー)を取得する方法は、3つあります。
Aggregate()
1つ目は、Aggregate()を使う方法です。
Aggeregate()を使ってDictionary(辞書)のValue(値)の最大値のKey(キー)を取得するには、Keyプロパティを使います。
まず、System.Linqを導入します。
using System.Linq;
DictionaryからAggregate()を呼び出します。
Aggregate()の引数に、第1引数と第2引数のValueプロパティで大きい方を返すラムダ式を指定します。
そして、Aggregate()の結果のKeyプロパティにアクセスします。
T maxKey = myDict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;
上記のKeyプロパティは、Aggregate()を呼び出した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 },
};
string maxKey = numbers.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;
Console.WriteLine(maxKey); //ten
}
}
foreachループ
2つ目は、foreachループを使う方法です。
まず、KeyValuePairの変数を用意します。
KeyValuePair<TKey, TValue> maxItem = new KeyValuePair<string, int>();
foreachでDictionaryをループします。
foreachのループ処理で、用意した変数よりループ変数の方がValueプロパティが大きい場合に、ループ変数を用意した変数に代入します。
foreach(var item in myDict)
{
if (item.Value > maxItem.Value)
{
maxItem = item;
}
}
あとは、用意した変数のKeyプロパティを取得します。
T maxKey = maxItem.Key;
上記のKeyプロパティは、DictionaryのValueの最大値のkeyを返します。
使用例
using System;
using System.Collections.Generic;
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 },
};
KeyValuePair<string, int> maxItem = new KeyValuePair<string, int>();
foreach(var item in numbers)
{
if (item.Value > maxItem.Value)
{
maxItem = item;
}
}
string maxKey = maxItem.Key;
Console.WriteLine(maxKey); //ten
}
}
OrderByDescending()
3つ目は、OrderByDescending()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、DictionaryからOrderByDescendingを呼び出します。
OrderByDescendingの引数に、引数のValueプロパティを返すラムダ式を指定します。
そして、OrderByDescending()のKeyプロパティにアクセスします。
T maxKey = myDict.OrderByDescending(x => x.Value).First().Key;
上記のKeyプロパティは、DictionaryのValueの最大値のkeyを返します。
使用例
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 },
};
string maxKey = numbers.OrderByDescending(x => x.Value).First().Key;
Console.WriteLine(maxKey); //ten
}
}
まとめ
Dictionary(辞書)のValueの最大値のKeyを取得する方法は、次の3つです。
- Aggregate()を使う方法
T maxKey = myDict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;
- foreachループを使う方法
- OrderByDescending()を使う方法
T maxKey = myDict.OrderByDescending(x => x.Value).First().Key;
コメント