Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to a dictionary via inline initialization of its container

I have the following City class. Each city object contains a dictionary which keys are language tags (let's say: "EN", "DE", "FR"...) and which values are the city names in the corresponding languages (ex: Rome / Rom etc.).

public class City: {   private IDictionary<string, string> localizedNames = new Dictionary<string, string>(0);   public virtual IDictionary<string, string> Names   {     get { return localizedNames ; }     set { localizedNames = value; }   } } 

Most of the cities have the same names whatever the language so the City constructor does actually creates the English mapping:

  public City(string cityName)   {     this.LocalizedNames.Add("EN", cityName);   } 

Here comes the question: is there a way to add the other values via inline initialization?

I tried different variations of the following without semantic success (does not compile):

AllCities.Add(new City("Rome") { Names["DE"] = "Rom" }; 

I also tried creating a new Dictionary, but this obviously overwrites the "EN" parameter:

AllCities.Add(new City("Rome") { Names = new Dictionary<string, string>() { { "DE", "Rom" } } }; 

Anybody know if this is possible?

like image 736
Timothée Bourguignon Avatar asked Jun 12 '12 14:06

Timothée Bourguignon


2 Answers

this is actual inline intialization:

private IDictionary<string, string> localizedNames = new Dictionary<string, string>{     {"key1","value1"},     {"key2","value2"} }; 
like image 69
zafar Avatar answered Oct 08 '22 00:10

zafar


AllCities.Add(new City("Rome") { Names = { { "DE", "Rom" }, { "...", "..." } } }); 

This is using initializer syntax to invoke the .Add method.

like image 32
usr Avatar answered Oct 07 '22 23:10

usr