以下の内容はhttps://baba-s.hatenablog.com/entry/2019/09/09/214900より取得しました。


【C#】Dictionary をソートする方法

方法1 - SortedDictionary を使用する

using System;
using System.Collections.Generic;

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

        foreach ( var n in table )
        {
            Console.WriteLine( n.Key + ": " + n.Value );
        }

        // 1: フシギダネ
        // 2: フシギソウ
        // 3: フシギバナ
    }
}
  • SortedDictionary を使用すると、要素を追加した段階で自動でソートされます

方法2 - OrderBy を使用する

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

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

        foreach ( var n in table.OrderBy( c => c.Key ) )
        {
            Console.WriteLine( n.Key + ": " + n.Value );
        }

        // 1: フシギダネ
        // 2: フシギソウ
        // 3: フシギバナ
    }
}
  • ソースコードの先頭に using System.Linq; を記述する必要があります



以上の内容はhttps://baba-s.hatenablog.com/entry/2019/09/09/214900より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14