C# 辞書を値でソートする

  • 作成日 2022.10.01
  • C#
C# 辞書を値でソートする

C#で、辞書を値でソートするサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Microsoft Visual Studio Community 2022 Version 17.2.6

辞書を値でソート

辞書を値でソートするには、「Linq」でクエリを使用します。

using System;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {

            Dictionary<int, string> dict = new Dictionary<int, string>
            {
                [0] = "ccc",
                [1] = "bbb",
                [2] = "aaa",
                [3] = "eee",
                [4] = "bbb",
                [5] = "ccc"
            };

            var sortedDict = from entry in dict orderby entry.Value ascending select entry;

            foreach (var v in sortedDict)
            {
                Console.WriteLine(v);
            }

        }

    }
}

実行結果

空の辞書

空の辞書に実行した場合は、空のままになります。

using System;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {

            Dictionary<int, string> dict = new Dictionary<int, string>
            {
            };

            var sortedDict = from entry in dict orderby entry.Value ascending select entry;

            foreach (var v in sortedDict)
            {
                Console.WriteLine(v);
            }

        }

    }
}

実行結果