在 C# 中將字典轉換為列表集合

Syed Hassan Sabeeh Kazmi 2023年10月12日
在 C# 中將字典轉換為列表集合

在 C# 中,可以使用作為 System.Linq 擴充套件的一部分的 ToList() 方法將字典轉換為列表。字典不能直接轉換為 List<string>,因為字典的返回型別是 KeyCollection

該列表類似於 ArrayList,唯一的區別是該列表是通用的並且具有獨特的屬性。

本教程將教你如何在 C# 中將字典轉換為列表集合。

C# 中使用 ToList() 方法將字典轉換為列表集合

C# 中的字典接受兩個引數,第一個是鍵,第二個是值。在將不同的資料及其值新增到列表時,該字典很有用。

要將字典值轉換為列表集合,我們可以通過其內建的 ToList() 方法將此通用列表轉換。列表和字典都儲存資料集合並且是相似的;兩者都是 .NET 框架的隨機訪問資料結構。

字典基於雜湊表,這是一種查詢事物的有效演算法。另一方面,列表逐個元素地進行,直到每次都從頭到尾找到結果。

在 C# 中使用 System.Collections.GenericSystem.Linq 名稱空間很容易將字典轉換為列表集合。在字典集合上呼叫 ToList(),產生 KeyValuePair 例項的列表。

// add `System.Collections.Generic` and `System.Linq` namespaces
using System;
using System.Collections.Generic;
using System.Linq;

class ConDtoLCol {
  static void Main() {
    // create a Dictionary
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict["cat"] = 1;
    dict["dog"] = 4;
    dict["mouse"] = 2;
    dict["rabbit"] = -1;

    // call ToList to convert the `dict` Dictionary to List
    List<KeyValuePair<string, int>> list = dict.ToList();

    // loop over List to show successful conversion
    foreach (KeyValuePair<string, int> pair in list) {
      Console.WriteLine(pair.Key);
      Console.WriteLine("   {0}", pair.Value);
    }
  }
}

輸出:

cat
   1
dog
   4
mouse
   2
rabbit
   -1

如果要將字典的鍵轉換為 C# 中的列表集合,可以使用:

List<string> listNumber = dicNumber.Keys.ToList();

此外,要將字典的值轉換為 C# 中的列表集合,你可以使用:

List<string> listNumber = dicNumber.Values.ToList();

.NET 框架字典表示鍵和值的集合。字典鍵的主要目的是允許使用者獲取字典值的通用列表(集合)。

此外,你可以使用 values 屬性來獲取字典值的通用列表。在本文中,你學習了在 C# 中將字典的鍵和值轉換為列表的最有效方法。

Syed Hassan Sabeeh Kazmi avatar Syed Hassan Sabeeh Kazmi avatar

Hassan is a Software Engineer with a well-developed set of programming skills. He uses his knowledge and writing capabilities to produce interesting-to-read technical articles.

GitHub

相關文章 - Csharp Dictionary

相關文章 - Csharp List