Thursday, April 26, 2012

How to gracefully add an existing key to dictionary c#

I have written some code that will gracefully add a key to dictionary. The goal was not to throw exception even if someone adds a key accidentally.  There are many arguments around this but it is the design that drove us to this. We could use a list that stores a class of Param with key and value as properties.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Example
  5. {
  6.     internal class Program
  7.     {
  8.         private static readonly Dictionary<string, int> dict = new Dictionary<string, int>();
  9.  
  10.         public static void Main(string[] args)
  11.         {
  12.             #region JunkCode
  13.  
  14.             AddParam("key", 0);
  15.             AddParam("key", 0);
  16.             AddParam("key", 0);
  17.             AddParam("key", 0);
  18.             AddParam("key", 0);
  19.             AddParam("key", 0);
  20.             AddParam("key", 0);
  21.             AddParam("key", 0);
  22.             AddParam("key", 0);
  23.             AddParam("key", 0);
  24.  
  25.             #endregion
  26.  
  27.             foreach (var kvp in dict)
  28.             {
  29.                 Console.WriteLine(kvp.Key);
  30.             }
  31.  
  32.             Console.Read();
  33.         }
  34.  
  35.         private static void AddParam(string key, int value)
  36.         {
  37.             if (!dict.ContainsKey(key))
  38.             {
  39.                 dict.Add(key, value);
  40.             }
  41.             else
  42.             {
  43.                 dict.Add(SubstituteParamName(key), value);
  44.             }
  45.         }
  46.  
  47.         private static string SubstituteParamName(string paramName)
  48.         {
  49.             string baseParamName = paramName;
  50.             string actualParamName = paramName;
  51.             int index = 0;
  52.  
  53.             while (dict.ContainsKey(actualParamName))
  54.             {
  55.                 actualParamName = baseParamName + "(" + ++index + ")";
  56.             }
  57.             return actualParamName;
  58.         }
  59.     }
  60. }

No comments:

Post a Comment