【发布时间】: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<string>(inventory.Keys) -
请记住,扩展方法甚至可以被称为:
Enumerable.ToList(inventory.Keys),因为 ToList() 是 List<TSource> ToList<TSource>(this IEnumerable<TSource> source),其中this IEnumerable<TSource> source甚至可以显式传递(在调试器,当你没有使用System.Linqdefinde) -
@xanatos -
Enumerable类在System.Linq中,所以无论如何都需要添加命名空间。 -
@RohitVats 但至少 Visual Studio 会建议 :-)... 你是对的,确切的命令是
System.Linq.Enumerable.ToList(inventory.Keys)
标签: c# list dictionary