在 C# 中按值对字典排序

Muhammad Maisam Abbas 2024年2月16日
  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