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

Time:05-24

I am working on .NET CORE 6. I have nested Dictionary<int, string> where I am adding value in loop to nested dictionary from string. The string holds multiple record where each record holds 15 columns hence dictionary is useful to hold keys.

After 15 iteration, I add nested/ child dictionary to parent Dictionary<string, string> and then I set nested dictionary to start again from counter 0. The issue is once I clear nested dictionary using Clear(), it also clear data from Parent dictionary. I need help on this and how I can approach to avoid that, 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;
    }

CodePudding user response:

Dictionary<TKey, TValue> is a reference type. Use the copy constructor of Dictionary<TKey, TValue> to create a new collection instance.

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