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

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
}
}
コメント