4

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

5
  • 1
    yes, you also need using System.Linq;, because that's where the .ToList() extension method is defined Commented Aug 11, 2013 at 16:12
  • 1
    Don't include System.Linq; if you only need ToList() for this once instance, just call new List<string>(inventory.Keys) Commented Aug 11, 2013 at 16:16
  • And remember, an extension method can even be called like: Enumerable.ToList(inventory.Keys), because ToList<T>() is List<TSource> ToList<TSource>(this IEnumerable<TSource> source), where the this IEnumerable<TSource> source can even be passed explicitly (useful in the debugger, when you don't have the using System.Linq definde) Commented Aug 11, 2013 at 16:17
  • @xanatos - Enumerable class is in System.Linq so namespace needs to be added anyways. Commented Aug 11, 2013 at 16:20
  • @RohitVats But at least the Visual Studio will suggest it :-)... You are right, the exact command is System.Linq.Enumerable.ToList(inventory.Keys) Commented Aug 11, 2013 at 16:23

3 Answers 3

13

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I used the new/different ctor - I did not need to and linq just for this. I have to go back and see why i did not notice that in the docs - regarding linq inclusion
2

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

Comments

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

1 Comment

I wanted to avoid having to explicitly make my own list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.