Dav*_*Dev 3 c# linq-to-objects
我有一个方法,取一个List<int>ID,这是一个ID列表.我的数据源是Dictionary<int, string>整数是我想要的列表.有没有比下面的代码更好的方法来获得这个?
var list = new List<int>();
foreach (var kvp in myDictionary)
{
list.Add(pair.Key);
}
ExecuteMyMethod(list);
Run Code Online (Sandbox Code Playgroud)
Tho*_*que 14
你可以做到
var list = myDictionary.Keys.ToList();
Run Code Online (Sandbox Code Playgroud)
要么
var list = myDictionary.Select(kvp => kvp.Key).ToList();
Run Code Online (Sandbox Code Playgroud)
是的,您可以Keys在列表的构造函数中使用该集合:
List<int> list = new List<int>(myDictionary.Keys);
Run Code Online (Sandbox Code Playgroud)