在 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