Tutorial :How do I Copy the Values of an IDictionary into an IList Object in .Net 2.0?


If I have a:

Dictionary<string, int>  

How do I copy all the values into a:



The solution needs to be something compatible with the 2.0 CLR version, and C# 2.0 - and I really dont have a better idea, other than to loop through the dictionary and add the values into the List object one-by-one. But this feels very inefficient.

Is there a better way?


It's probably worth noting that you should step back and ask yourself if you really need the items stored in a list with random indexed access, or if you just need to enumerate each of the keys or values from time to time.

You can easily iterate over the ICollection of MyDictionary.Values.

foreach (int item in dict.Values) { dosomething(item); }  

Otherwise, if you actually need to store it as an IList, there's nothing particularly inefficient about copying all the items over; that's just an O(n) operation. If you don't need to do it that often, why worry? If you're annoyed by writing the code to do that, use:

IList<int> x=new List<int>(dict.Values);  

which wraps the code that you'd write into a copy constructor that already implements the code you were planning to write. That's lines-of-code-efficient, which is probably what you actually care about; it's no more space-or-time efficient than what you'd write.


This should work even on 2.0 (forgive the C# 3.0 use of "var"):

var dict = new Dictionary<string, int>();  var list = new List<int>(dict.Values);  


Try the following

public static class Util {    public List<TValue> CopyValues<TKey,TValue>(Dictionary<TKey,TValue> map) {      return new List<TValue>(map.Values);    }  }  

You can then use the method like the following

Dictionary<string,int> map = GetTheDictionary();  List<int> values = Util.CopyValues(map);  


If you can use an IEnumerable<int> or ICollection<int> instead of a List<int> you can just use the Value collection from the dictionary without copying anything.

If you need a List<int> then you have to copy all the items. The constructor of the list can do the work for you, but each item still has to be copied, there is no way around that.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »