[英]In C# how do I get a list of the keys from a dictionary?
我有以下代码:
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 System.Collections.Generic;
我需要什么?
编辑
List < string> inventoryList = new List<string>(inventory.Keys);
有效,但刚收到有关LINQ的评论
您可以使用Enumerable.ToList
扩展方法,在这种情况下,您需要添加以下内容:
using System.Linq;
或者您可以使用List<T>
的不同构造函数 ,在这种情况下,您不需要新的using
语句,并且可以执行此操作:
List<string> inventoryList = new List<string>(inventory.Keys);
缺少using System.Linq
,其中包含ToList()
扩展方法。
我认为您应该能够循环访问Keys集合,如下所示:
foreach (string key in inventory.Keys)
{
Console.WriteLine(key + ": " + inventory[key].ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.