A ternary operator with multiple arguments

I have a dictionary that is defined as:

Dictionary<string, string> typeLookup = new Dictionary<string, string>(); 

I want to add a key / value to the dictionary based on which language the user has selected, which in my case was found with:

 Request.Cookies["language"].Value == "ja-JP" //if true, Japanese, if false, English 

I could just do if / elses, but I'm curious if there is a way to make this work:

 typeLookup.Add((Request.Cookies["language"].Value == "ja-JP") ? "6","中間" : "6","Q2"); 

As a dictionary, you need to specify two lines. This does not work, giving me "Syntax error": "Expected." Is this a lost cause, or is there something I need to change / add in order for this idea to work?

+4
source share
2 answers

Since both sides of conditional use use the same key, you can trick:

 typeLookup.Add("6", (Request.Cookies["language"].Value == "ja-JP") ? "中間":"Q2"); 

In the general case, however, you will get a significantly uglier, repeating expression:

 typeLookup.Add( (Request.Cookies["language"].Value == "ja-JP") ? "6" : "7" , (Request.Cookies["language"].Value == "ja-JP") ? "中間" : "Q2" ); 
+2
source

Assuming the key always remains unchanged, short the triple to apply only to the value (also, if you compare several times, I would save the value isEnglish or isJapanese ):

 typeLookup.add("6", Request.Cookies["language"] == "ja-JP" ? "中間" : "Q2"); 

However, you can always create an assistant:

 Dictionary<string, string> typeLookup = new Dictionary<string, string>(); System.Action<String,String,String> japEng = (key,japaneseValue,englishValue) => { if (Request.Cookies["language"].Value == "ja-JP") typeLookup.Add(key, japaneseValue); else typeLookup.Add(key, englishValue); }; japEng("6", "中間", "Q2"); 

Another option ...

+1
source

Source: https://habr.com/ru/post/1441695/


All Articles