在 C# 中按值對字典排序

Muhammad Maisam Abbas 2023年1月30日 2021年4月29日
  1. 使用 C# 中的 List 方法按值對字典進行排序
  2. 使用 C# 中的 Linq 方法按值對字典進行排序
在 C# 中按值對字典排序

本教程將介紹在 C# 中按值對字典排序的方法。

使用 C# 中的 List 方法按值對字典進行排序

C# 字典資料結構key:value 對的形式儲存資料。不幸的是,在 C# 中,沒有內建的方法可以按值對字典進行排序。我們必須將字典轉換為元組列表,然後對列表進行排序。以下程式碼示例向我們展示瞭如何在 C# 中按值對具有列表的字典進行排序。

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

namespace sort_dictionary_by_value
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> myDict = new Dictionary<string, int>();
            myDict.Add("one", 1);
            myDict.Add("four", 4);
            myDict.Add("two", 2);
            myDict.Add("three", 3);
            var myList = myDict.ToList();

            myList.Sort((pair1, pair2) => pair1.Value.CompareTo(pair2.Value));
            foreach (var value in myList)
            {
                Console.WriteLine(value);
            }
        }
    }
}

輸出:

[one, 1]
[two, 2]
[three, 3]
[four, 4]

我們建立了字典 myDict,並按整數值對其進行了排序。我們首先使用 C# 中的 ToList() 函式將 myDict 轉換為元組列表 myList。然後,我們使用 Linq 對 myList 進行排序,並顯示值。

使用 C# 中的 Linq 方法按值對字典進行排序

我們也可以直接按值對字典排序,而無需先將其轉換為列表。Linq 或語言整合查詢用於在 C# 中執行類似 SQL 的查詢。我們可以使用 Linq 按值對字典進行排序。下面的程式碼示例向我們展示瞭如何在 C# 中使用 Linq 按值對字典進行排序。

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

namespace sort_dictionary_by_value
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> myDict = new Dictionary<string, int>();
            myDict.Add("one", 1);
            myDict.Add("four", 4);
            myDict.Add("two", 2);
            myDict.Add("three", 3);

            var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
            foreach (var value in sortedDict)
            {
                Console.WriteLine(value);
            }
        }
    }
}

輸出:

[one, 1]
[two, 2]
[three, 3]
[four, 4]

我們建立了字典 myDict,並使用 C# 中的 Linq 將其按整數值排序。我們將排序後的字典儲存在 sortedDict 內,並顯示值。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp Dictionary