replace key field in dictionary data type

ankit goel 766 Reputation points
2022-12-15T09:51:23.793+00:00

@Jack J Jun , sir in the same excel project, I have used a dictionary type as advised but later now after filling it , i want to change some of its key name in key, value string. The documentation says we cant change it . Can you provide some code to accomplish this . Thanks in advance .

 Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();  
        for (int i = 0; i < list1.Count; i++)  
        {  
            string key = list1[i];  
            List<string> l = new List<string>();  
            for (var item=1;item<listnew.Count;item++) // deliberately starts from 1   
            {  
                if (listnew[item][0].ToString().StartsWith(key))  
                {  
                    l.Add(listnew[item][0].ToString());  
                }  

            }  
            dic.Add(key, l);  
        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,542 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,211 Reputation points Microsoft External Staff
    2022-12-16T05:56:14.53+00:00

    Hi @ankit goel ,
    Since you can't change the key of an existing dictionary entry. You'll have to remove/add using a new key.
    You can refer to the code below.

                while (dic.ContainsKey("1")){  
                    dic.Add("a", dic["1"]);  
                    dic.Remove("1");  
                }  
    

    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.