Devo aggiungere coppie di chiavi/oggetti a un dizionario, ma ovviamente devo prima controllare se la chiave esiste già altrimenti ottengo un errore "già esistente nel dizionario". Il codice qui sotto risolve questo problema ma è goffo.C'è un modo più elegante di aggiungere un elemento ad un dizionario <> in modo sicuro?
Che cosa è un modo più elegante di fare questo senza fare un metodo di stringa di helper come questo?
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;
}
}
}
}
eccellente, non si rese conto semplice assegnazione ha curato l'add/problema di sovrascrittura, bello. –