コガネブログ

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

【C#】Dictionary を逆順に参照する方法

ソースコード

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

public static class Program
{
    private static void Main()
    {
        var table = new Dictionary<int, string>
        {
            { 1, "フシギダネ" },
            { 2, "フシギソウ" },
            { 3, "フシギバナ" },
        };
        
        // 逆順の Dictionary を作成
        var reversed = table
                       .Reverse()
                       .ToDictionary( c => c.Key, c => c.Value );

        foreach ( var n in reversed )
        {
            Console.WriteLine( n );
        }
        
        // 3, フシギバナ
        // 2, フシギソウ
        // 1, フシギダネ
    }
}
  • ソースコードの先頭に using System.Linq; を追加する必要があります