如何在应用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>的复制构造函数创建一个新的集合实例。

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

相关内容

  • 没有找到相关文章

最新更新