Tim
Tim

Reputation: 20360

In C# how do I get a list of the keys from a dictionary?

I have the following code:

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();

But I get the following error:

'System.Collections.Generic.Dictionary.KeyCollection' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Collections.Generic.Dictionary.KeyCollection' could be found (are you missing a using directive or an assembly reference?)

Am I missing a using directive? Is there something other than

using System.Collections.Generic;

that I need?

EDIT

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

works, but just got a comment regarding LINQ

Upvotes: 4

Views: 5738

Answers (3)

Rod Stephens
Rod Stephens

Reputation: 1

I think you should be able to loop through the Keys collection as in:

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

Upvotes: -1

Sam Harwell
Sam Harwell

Reputation: 99859

You can either use the Enumerable.ToList extension method, in which case you need to add the following:

using System.Linq;

Or you can use a different constructor of List<T>, in which case you don't need a new using statement and can do this:

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

Upvotes: 13

Rohit Vats
Rohit Vats

Reputation: 81243

using System.Linq is missing which contains ToList() extension method.

Upvotes: 2

Related Questions