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
- using System;
- using System.Collections.Generic;
- namespace Example
- {
- internal class Program
- {
- private static readonly Dictionary<string, int> dict = new Dictionary<string, int>();
- public static void Main(string[] args)
- {
- #region JunkCode
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- AddParam("key", 0);
- #endregion
- foreach (var kvp in dict)
- {
- Console.WriteLine(kvp.Key);
- }
- Console.Read();
- }
- private static void AddParam(string key, int value)
- {
- if (!dict.ContainsKey(key))
- {
- dict.Add(key, value);
- }
- else
- {
- dict.Add(SubstituteParamName(key), value);
- }
- }
- private static string SubstituteParamName(string paramName)
- {
- string baseParamName = paramName;
- string actualParamName = paramName;
- int index = 0;
- while (dict.ContainsKey(actualParamName))
- {
- actualParamName = baseParamName + "(" + ++index + ")";
- }
- return actualParamName;
- }
- }
- }
No comments:
Post a Comment