简体   繁体   English

字典 <string, List<int> &gt;复制到另一本词典

[英]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. 一切顺利,但是如果密钥已经存在,我只要将List中的值添加到另一个字典中。 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. 我们也加入了我的记录,也是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. 您正在将字典值设置为原始列表的引用List<T>是引用类型) - 因此当您向该列表添加项目时,它也会显示在字典中 - 两者都引用相同的列表。

Instead you can just force creation of a new list for your dictionary: 相反,您可以强制为字典创建新列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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