How to extract List <int> from dictionary <int, string>?

I have a method that accepts List<int>

which is a list of ids. The source of my data is Dictionary<int, string>

where integers are what I want in the list. Is there a better way to get this than the following code?

var list = new List<int>();
foreach (var kvp in myDictionary)
{
    list.Add(pair.Key);
}

ExecuteMyMethod(list);

      

+2


a source to share


3 answers


You could do

var list = myDictionary.Keys.ToList();

      



or

var list = myDictionary.Select(kvp => kvp.Key).ToList();

      

+13


a source


Yes, you can use a collection Keys

in the list constructor:



List<int> list = new List<int>(myDictionary.Keys);

      

+6


a source


Like Guffa, this is something that is light and elegant. or

List<int> nList = myDictionary.Keys.ToList<int>();

      

+1


a source







All Articles