Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 774
Ash Avatar asked Dec 05 '22 06:12

Ash


1 Answers

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.

like image 186
JasonTrue Avatar answered Dec 09 '22 14:12

JasonTrue