简体   繁体   中英

Dictionary<string, List<int>> copy to another Dictionary

I have a problem with copying the values ​​of the numbers into another dictionary. Everything goes well, but as soon as I add values ​​from a List to another dictionary if the key already exists. I do not understand how it is possible that the same values ​​are added to the dictionary as well as going through.

   foreach (KeyValuePair<string, List<int>> record in dictonaryUnStem)

        {
            arrayWord = record.Key.ToCharArray();
            st.add(arrayWord);
            stemWord = st.stem();

            if (!dictonaryStem.ContainsKey(stemWord))
            {
                dictonaryStem.Add(stemWord, record.Value);
            }
            else
            {
                foreach (int i in record.Value)
                {
                    dictonaryStem[stemWord].Add(i);
                }
            }
        }

When you add to another dictionary from the given key integers. We join me on the record, too integers dictionaryUnStem. It is a complete illogical.

stemWord = st.stem() 

gives me root word which is the key word in the first dictionary. In the list are stored position of that words in the text.

The problem is here:

dictonaryStem.Add(stemWord, record.Value);

You are setting the dictionary value to the reference of the original list ( List<T> is a reference type) - hence when you add an item to that list, it also shows up in the dictionary - both reference the same list.

Instead you can just force creation of a new list for your dictionary:

dictonaryStem.Add(stemWord, record.Value.ToList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM