How to add duplicate keys into the Dictionary

♀尐吖头ヾ 提交于 2019-12-02 18:09:40

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;

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

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.

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();
            }
         }
Nagesh Hugar
List< KeyValuePair < string, string>> listKeyValPair= new List< KeyValuePair< string, string>>();
KeyValuePair< string, string> keyValue= new KeyValuePair< string, string>("KEY1", "VALUE1");
listKeyValPair.Add(keyValue);

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!