How to iterate through Dictionary and change values?

后端 未结 8 462
灰色年华
灰色年华 2020-12-02 17:52
Dictionary myDict = new Dictionary();
//...
foreach (KeyValuePair kvp in myDict)
 {
     kvp.Value = Math.Round(kvp.Value,          


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 18:37

    I noticed that fastest way (at this moment) iterate over Dictionary with modify is:

    //Just a dumb class
    class Test
    {
        public T value;
    
        public Test() { }
        public Test(T v) { value = v; }
    }
    
    Dictionary> dic = new Dictionary>();
    //Init dictionary
    foreach (KeyValuePair pair in dic)
    {
        pair.Value.value = TheObject;//Modify
    }
    

    VS

    List keys = new List(dic.Keys); //This is fast operation   
    foreach (int key in keys)
    {
        dic[key] = TheObject;
    }
    

    First one takes about 2.2s and second one 4.5s (tested dictionary size of 1000 and repeated 10k time, changing dictionary size to 10 didn't change the ratios). Also there wasn't a big deal with getting the Key list, dictionary[key] value get is just slow VS built in iteration. Also if you want even more speed use hard coded type to dumb ("Test") class, with that I got it about 1.85s (with hard coded to "object").

    EDIT:

    Anna has posted the same solution before: https://stackoverflow.com/a/6515474/766304

提交回复
热议问题