30

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.

3
  • 1
    As other have said, it is not possible to add duplicate key in dictionary. How about using Dictionary<string, List<string>>? Then check if the key exist then add the line in the list value for that key and if the key does not exist then create a new entry in the dictionary. Commented Mar 10, 2014 at 10:31
  • @samar how to check for duplicate keys in Dictionary? Commented Mar 10, 2014 at 10:48
  • Possible duplicate of Duplicate keys in .NET dictionaries? Commented Mar 15, 2018 at 12:21

6 Answers 6

36

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;
Sign up to request clarification or add additional context in comments.

5 Comments

how to check for duplicate keys and delete previous value from Dictionary?
@Ram see updated solution. You also can use Linq to create dictionary from last values only
It's good to note that a lookup does not implement ICollection. So there are no Add, Remove, Clear Contains, or CopyTo methods. Or Count property.
Why not just use 'previousLines[dialedno] = line' without ContainsKey check?
@RobHinchliff 101% agree with you
27

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);

1 Comment

Thank you for an actual answer. So much more functional than can't be done.
9

Its not possible to add duplicate items to a Dictionary - an alternative is to use the Lookup class.

Enumerable.ToLookup Method

Creates a generic Lookup from an IEnumerable.

1 Comment

Note that this class does not implement ICollection
2

Example:

class Program
        {
             private static List<KeyValuePair<string, int>> d = new List<KeyValuePair<string, int>>();

            static void Main(string[] args)
            {
                 d.Add(new KeyValuePair<string, int>("joe", 100));
                 d.Add(new KeyValuePair<string, int>("joe", 200));
                 d.Add(new KeyValuePair<string, int>("jim", 100));
                 var result = d.Where(x => x.Key == "joe");
                foreach(var q in result)
                    Console.WriteLine(q.Value   );
                Console.ReadLine();
            }
         }

Comments

0
List< KeyValuePair < string, string>> listKeyValPair= new List< KeyValuePair< string, string>>();
KeyValuePair< string, string> keyValue= new KeyValuePair< string, string>("KEY1", "VALUE1");
listKeyValPair.Add(keyValue);

1 Comment

This is almost the same code as in this answer
0

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<int, int>();
        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://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.tryadd?view=netframework-4.7.2

1 Comment

This worn't help since still the dict will have unique keys. Consider updating your answer as per the question Dictionary<string, string>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.