4

I have a dictionary defined as:

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

I want to add a key/value to the dictionary based on what language the user has selected, which in my case is 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 some way to make this work:

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

As it's a Dictionary, two strings need to be specified. This doesn't work, giving me "Syntax error, ':' expected". Is this a lost cause, or is there something I need to change/add to make this idea work?

CptSupermrkt
  • 6,844
  • 12
  • 56
  • 87
  • Your example could be done by moving the first arg outside of the statement. Like `typeLookup.Add("6", (Request.Cookies["language"].Value == "ja-JP") ? "中間" : "Q2");`. If the first value can be different, the example should show that. – cHao Oct 24 '12 at 01:12

2 Answers2

2

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

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

In general case, however, you would end up with a considerably uglier, repetitive, statement:

typeLookup.Add(
    (Request.Cookies["language"].Value == "ja-JP") ? "6" : "7"
,   (Request.Cookies["language"].Value == "ja-JP") ? "中間" : "Q2"
);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Assuming the key always remains the same, short-circuit the ternary to only apply to the value (also, if you're comparing multiple times I'd store an isEnglish or isJapanese value):

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

However, you could always create a helper:

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");

Just another option...

Brad Christie
  • 100,477
  • 16
  • 156
  • 200