开发者

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

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 int开发者_StackOverflow中文版egers 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);


You could do

var list = myDictionary.Keys.ToList();

Or

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


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

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜