在 C# 中對 KeyValuePair 進行排序


使用 Sort 方法對 KeyValuePairs 集合進行排序。

首先,設定集合 −

var myList = new List<KeyValuePair<int, int>>();

// adding elements
myList.Add(new KeyValuePair<int, int>(1, 20));
myList.Add(new KeyValuePair<int, int>(2, 15));
myList.Add(new KeyValuePair<int, int>(3, 35));
myList.Add(new KeyValuePair<int, int>(4, 50));
myList.Add(new KeyValuePair<int, int>(5, 25));

要進行排序,請使用 Sort() 方法。在此基礎上,我們使用 CompareTo() 方法比較值 −

myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));

以下是完整程式碼 −

示例

 即時演示

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      var myList = new List<KeyValuePair<int, int>>();
      // adding elements
      myList.Add(new KeyValuePair<int, int>(1, 20));
      myList.Add(new KeyValuePair<int, int>(2, 15));
      myList.Add(new KeyValuePair<int, int>(3, 35));
      myList.Add(new KeyValuePair<int, int>(4, 50));
      myList.Add(new KeyValuePair<int, int>(5, 25));
      Console.WriteLine("Unsorted List...");
      foreach (var val in myList) {
         Console.WriteLine(val);
      }
      // Sort Value
      myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));
      Console.WriteLine("Sorted List...");
      foreach (var val in myList) {
         Console.WriteLine(val);
      }
   }
}

輸出

Unsorted List...
[1, 20]
[2, 15]
[3, 35]
[4, 50]
[5, 25]
Sorted List...
[4, 50]
[3, 35]
[5, 25]
[1, 20]
[2, 15]

更新於: 2020-06-22

665 次檢視

開啟你的 職業生涯

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.