在C#中如何从字典中获取键列表?

Tim*_*Tim 3 c# dictionary list

我有以下代码:

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();
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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

我错过了使用指令吗?还有其他的东西吗?

using System.Collections.Generic;
Run Code Online (Sandbox Code Playgroud)

我需要什么?

编辑

List < string> inventoryList = new List<string>(inventory.Keys);
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*ell 11

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

using System.Linq;
Run Code Online (Sandbox Code Playgroud)

或者您可以使用不同的构造函数List<T>,在这种情况下,您不需要新的using语句,并且可以执行此操作:

List<string> inventoryList = new List<string>(inventory.Keys);
Run Code Online (Sandbox Code Playgroud)