应用 Dictionary.Clear() 时如何避免字典覆盖对象的引用值

How to avoid dictionary override reference value of object when apply Dictionary.Clear()

我正在研究 .NET CORE 6。我嵌套了 Dictionary<int, string>,我在循环中将值添加到字符串中的嵌套字典。该字符串包含多条记录,其中每条记录包含 15 列,因此字典可用于保存键。

15 次迭代后,我将嵌套/子字典添加到父 Dictionary<string, string>,然后我将嵌套字典设置为从计数器 0 重新开始。问题是一旦我使用 Clear() 清除嵌套字典,它还从父字典中清除数据。我需要这方面的帮助以及如何避免这种情况,dataItemDictionary.Clear();

 private Dictionary<string, Dictionary<int, string>> ConvertStream(string stream)
    {
        Dictionary<string, Dictionary<int, string>> dataDictionary = new Dictionary<string, Dictionary<int, string>>();

        Dictionary<int, string> dataItemDictionary = new Dictionary<int, string>();

        if (!string.IsNullOrWhiteSpace(stream))
        {
            string column = string.Empty;
            int dataItemDictionaryindex = 0;
            int dataDictionaryIndex = 0;
            int columnCounter = 16;

            foreach(char c in stream)
            {
                if(c.Equals('|'))
                {
                    dataItemDictionary.Add(dataItemDictionaryindex, column);

                    column = string.Empty;

                    dataItemDictionaryindex++;
                     
                    if (columnCounter == dataItemDictionaryindex)
                    {
                        Dictionary<int, string> data = new Dictionary<int, string>();

                        data = dataItemDictionary; // need help here...

                        dataDictionary.Add("Record@" + dataDictionaryIndex, data);

                        dataItemDictionary.Clear();

                        dataDictionaryIndex++;
                        columnCounter = columnCounter * (dataDictionaryIndex + 1);
                    }
                }
                else
                {
                    if (!c.Equals('\r') && !c.Equals('\n'))
                    {
                        column = column + c;
                    }              
                }
            }
        }
        return dataDictionary;
    }

Dictionary<TKey, TValue>Dictionary<TKey, TValue>reference type. Use the copy constructor 以创建新的集合实例。

Dictionary<int, string> data = new Dictionary<int, string>(dataItemDictionary);