How to add duplicate keys into the Dictionary

后端 未结 6 629
闹比i
闹比i 2021-01-31 17:37

I have some lines from text files that i want to add into the Dictionary.I am using Dictionary for the first time.While adding up starting lines it was Ok but suddenly i got err

6条回答
  •  别那么骄傲
    2021-01-31 18:42

    If your question is if you can add the same key twice, the answer is No. However if you want to just iterate through the item and then increase the count of the value for the particular Key, you can achieve that by using "TryAdd" method.

    var dict = new Dictionary();
            foreach (var item in array)
            {
                dict.TryAdd(item, 0);
                dict[item]++;
            }
    

    The same thing we are trying to achieve with if else, can be achieved with this method.``

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.tryadd?view=netframework-4.7.2

提交回复
热议问题