コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】Dictionary から最大値や最小値を持つ要素を検索する方法

方法1

using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    private static void Main()
    {
        var table = new Dictionary<string, int>
        {
            { "フシギダネ", 1 },
            { "フシギソウ", 2 },
            { "フシギバナ", 3 },
        };

        // 最大値を持つ要素を検索
        var maxValue = table.Values.Max();
        var maxElem  = table.FirstOrDefault( c => c.Value == maxValue );

        Console.WriteLine( maxElem );

        // 最小値を持つ要素を検索
        var minValue = table.Values.Min();
        var minElem  = table.FirstOrDefault( c => c.Value == minValue );

        Console.WriteLine( minElem );
    }
}
  • ソースコードの先頭に using System.Linq; を記述する必要があります

方法2

using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    private static void Main()
    {
        var table = new Dictionary<string, int>
        {
            { "フシギダネ", 1 },
            { "フシギソウ", 2 },
            { "フシギバナ", 3 },
        };

        // 最大値を持つ要素を検索
        var maxElem = table
                      .OrderByDescending( c => c.Value )
                      .FirstOrDefault();

        Console.WriteLine( maxElem );

        // 最小値を持つ要素を検索
        var minElem = table
                      .OrderBy( c => c.Value )
                      .FirstOrDefault();

        Console.WriteLine( minElem );
    }
}
  • ソースコードの先頭に using System.Linq; を記述する必要があります