मुझे एक शब्दकोश में कुंजी / ऑब्जेक्ट जोड़े जोड़ने की आवश्यकता है, लेकिन मुझे पहले यह जांचने की आवश्यकता है कि क्या कुंजी पहले से मौजूद है अन्यथा मुझे " कुंजी पहले से ही शब्दकोश में मौजूद है " त्रुटि मिलती है । नीचे दिया गया कोड इसे हल करता है लेकिन क्लंकी है।
इस तरह से एक स्ट्रिंग सहायक विधि बनाने के बिना इसे करने का एक और अधिक सुरुचिपूर्ण तरीका क्या है?
using System;
using System.Collections.Generic;
namespace TestDictStringObject
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> currentViews = new Dictionary<string, object>();
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2");
StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1");
foreach (KeyValuePair<string, object> pair in currentViews)
{
Console.WriteLine("{0} {1}", pair.Key, pair.Value);
}
Console.ReadLine();
}
}
public static class StringHelpers
{
public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, view);
}
else
{
dict[key] = view;
}
}
}
}