Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add duplicate keys into the Dictionary

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 error:

An item with the same key has already been added

Here in my code there are duplicate keys which i can not change.Here is my code in c#

Dictionary<string, string> previousLines = new Dictionary<string, string> { }; previousLines.Add(dialedno, line); 

Here dialedno is the key and line is the textfile line. Here is the code from which i am retrieving the given line based on key.

string tansferOrginExt = previousLines[dialedno]; 

So my concern is how to allow to add duplicate keys in Dictionary if possible and if not how can i get similar functionality.

like image 935
Ram Avatar asked Mar 10 '14 10:03

Ram


People also ask

Can we insert duplicate keys into a dictionary?

In Dictionary, the key cannot be null, but value can be. In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.

Can we repeat key in dictionary python?

Python dictionary doesn't allow key to be repeated.


Video Answer


2 Answers

how to allow to add duplicate keys in Dictionary

It is not possible. All keys should be unique. As Dictionary<TKey, TValue> implemented:

Every key in aDictionary<TKey, TValue> must be unique according to the dictionary's equality comparer.

Possible solutions - you can keep collection of strings as value (i.e. use Dictionary<string, List<string>>), or (better) you can use Lookup<TKey, TValue> instead of dictionary.


how to check for duplicate keys and delete previous value from Dictionary?

You can check if the key exists with previousLines.ContainsKey(dialedno) but if you always want to hold the last line, then just replace whatever dictionary had for the key, or add the new key if it is not in the dictionary:

previousLines[dialedno] = line; 
like image 64
Sergey Berezovskiy Avatar answered Oct 13 '22 09:10

Sergey Berezovskiy


We can Use a List of Key Value Pair

List<KeyValuePair<string, string>> myduplicateLovingDictionary= new List<KeyValuePair<string, string>>(); KeyValuePair<string,string> myItem = new KeyValuePair<string,string>(dialedno, line); myduplicateLovingDictionary.Add(myItem); 
like image 32
Ajay Bhasy Avatar answered Oct 13 '22 07:10

Ajay Bhasy