How to copy IDictionary values ​​to an IList in .Net 2.0?

If I have:

Dictionary<string, int>

How to copy all values ​​to a:

List<int> 

An object?

The solution should be something compatible with CLR version 2.0 and C # 2.0 - and I really have no better idea than to scroll through the dictionary and add values ​​to the List object one by one. But it seems very inefficient.

Is there a better way?

+3
source share
4 answers

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

ICollection MyDictionary.Values.

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

, IList, ; O (n). , ? , , :

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

, , , , . , , , ; , , .

+8

2.0 ( # 3.0 "var" ):

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

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

, ,

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

If you can use IEnumerable<int>or ICollection<int>instead List<int>, you can simply use the collection Valuefrom the dictionary without copying anything.

If you need List<int>, you need to copy all the elements. The list constructor can do your work, but each item still needs to be copied; there is no way around this.

0
source

Source: https://habr.com/ru/post/1706773/


All Articles