[英]How to extract List<int> from Dictionary<int, string>?
I have a method that takes a List<int>
, which is a list of IDs. 我有一个方法,它采用
List<int>
,这是一个ID列表。 The source of my data is a Dictionary<int, string>
where the integers are what I want a list of. 我的数据源是
Dictionary<int, string>
,其中整数是我想要的列表。 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();
是的,您可以在列表的构造函数中使用Keys
集合:
List<int> list = new List<int>(myDictionary.Keys);
Like Guffa said that's some thing which is easy and elegant. 就像Guffa说的那样,有些事情既简单又优雅。 or
要么
List<int> nList = myDictionary.Keys.ToList<int>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.