【问题标题】:In C# how do I get a list of the keys from a dictionary?在 C# 中,如何从字典中获取键列表?
【发布时间】:2013-08-11 16:11:54
【问题描述】:

我有以下代码:

Dictionary <string, decimal> inventory;
// this is passed in as a parameter.  It is a map of name to price
// I want to get a list of the keys.
// I THOUGHT I could just do:

List<string> inventoryList = inventory.Keys.ToList();

但我收到以下错误:

'System.Collections.Generic.Dictionary.KeyCollection' 不包含“ToList”的定义,也没有扩展方法 'ToList' 接受类型的第一个参数 'System.Collections.Generic.Dictionary.KeyCollection' 可以找到(您是否缺少 using 指令或程序集 参考?)

我是否缺少 using 指令?除了

using System.Collections.Generic;

我需要吗?

编辑

List < string> inventoryList = new List<string>(inventory.Keys);

有效,但刚刚收到关于 LINQ 的评论

【问题讨论】:

  • 是的,你还需要using System.Linq;,因为这是定义.ToList()扩展方法的地方
  • 不包括 System.Linq;如果您需要 ToList() 用于此一次实例,只需调用 new List&lt;string&gt;(inventory.Keys)
  • 请记住,扩展方法甚至可以被称为:Enumerable.ToList(inventory.Keys),因为 ToList() 是 List&lt;TSource&gt; ToList&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source),其中 this IEnumerable&lt;TSource&gt; source 甚至可以显式传递(在调试器,当你没有使用 System.Linqdefinde)
  • @xanatos - Enumerable 类在 System.Linq 中,所以无论如何都需要添加命名空间。
  • @RohitVats 但至少 Visual Studio 会建议 :-)... 你是对的,确切的命令是 System.Linq.Enumerable.ToList(inventory.Keys)

标签: c# list dictionary


【解决方案1】:

您可以使用Enumerable.ToList 扩展方法,在这种情况下您需要添加以下内容:

using System.Linq;

或者您可以使用different constructor of List&lt;T&gt;,在这种情况下您不需要新的using 语句并且可以这样做:

List<string> inventoryList = new List<string>(inventory.Keys);

【讨论】:

  • 谢谢-我使用了新的/不同的ctor-我不需要为此而使用linq。我必须回去看看为什么我没有在文档中注意到这一点 - 关于 linq 包含
【解决方案2】:

using System.Linq 缺失,其中包含ToList() 扩展方法。

【讨论】:

    【解决方案3】:

    我认为您应该能够循环访问 Keys 集合,如下所示:

    foreach (string key in inventory.Keys)
    {
        Console.WriteLine(key + ": " + inventory[key].ToString());
    }
    

    【讨论】:

    • 我想避免自己明确列出清单。
    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    相关资源
    最近更新 更多