如何将IDictionary的值复制到.Net 2.0中的IList对象中?

Ash*_*Ash 3 .net c# generics performance c#-2.0

如果我有:

Dictionary<string, int>
Run Code Online (Sandbox Code Playgroud)

如何将所有值复制到:

List<int> 
Run Code Online (Sandbox Code Playgroud)

宾语?

解决方案需要与2.0 CLR版本和C#2.0兼容 - 除了循环遍历字典并将值逐个添加到List对象之外,我真的没有更好的想法.但这感觉非常低效.

有没有更好的办法?

Jas*_*rue 8

值得注意的是,您应该退后一步,问自己是否确实需要存储在具有随机索引访问权限的列表中的项目,或者您是否需要不时枚举每个键或值.

您可以轻松地迭代MyDictionary.Values的ICollection.

foreach (int item in dict.Values) { dosomething(item); }
Run Code Online (Sandbox Code Playgroud)

否则,如果您确实需要将其存储为IList,那么复制所有项目并不是特别低效; 这只是一个O(n)操作.如果您不需要经常这样做,为什么要担心?如果您为编写代码而烦恼,请使用:

IList<int> x=new List<int>(dict.Values);
Run Code Online (Sandbox Code Playgroud)

它将您编写的代码包装到已经实现了您计划编写的代码的复制构造函数中.这是代码效率的线,这可能是你真正关心的; 它没有比你写的更有空间或时间效率.


Mat*_*ton 5

这甚至应该在2.0上工作(原谅C#3.0使用"var"):

var dict = new Dictionary<string, int>();
var list = new List<int>(dict.Values);
Run Code Online (Sandbox Code Playgroud)