views:

441

answers:

4

If I have a:

Dictionary<string, int>

How do I copy all the values into a:

List<int>

Object?

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?

A: 

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);
JaredPar
IIRC C# 2.0 can't infer the genric types, so you have to specify them in the call: Util.CopyValues<string,int>(map)
Guffa
@Guffa, my code will work in C# 2.0 and up. C# cannot do local type inference in 2.0 but it can still do method type inference.
JaredPar
+4  A: 

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);
Matt Hamilton
A: 

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.

Guffa
+6  A: 

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.

JasonTrue