views:

126

answers:

3

I have a method that takes a List<int>, which is a list of IDs. The source of my data is a Dictionary<int, string> where the integers are what I want a list of. 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);
+12  A: 

You could do

var list = myDictionary.Keys.ToList();

Or

var list = myDictionary.Select(kvp => kvp.Key).ToList();
Thomas Levesque
the beauty is in the simplicity :-)
DaveDev
+5  A: 

Yes, you can use the Keys collection in the constructor of the list:

List<int> list = new List<int>(myDictionary.Keys);
Guffa
This solution is not only elegant, but also works on C# 2 and .NET 2.
Jon Skeet
A: 

Like Guffa said that's some thing which is easy and elegant. or

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