Switch statement.Contains statement

Is it possible to make a switch statement that validates an instruction Message.Contains?

So instead:

if (ex.Message.Contains("hnummer"))
{
    MessageBox.Show("Deze laptop staat al in de lijst");
}
if (ex.Message.Contains("serienummmer"))
{
    MessageBox.Show("Dit serienummer staat al in de lijst");
}
if (ex.Message.Contains("olcnummer"))
{
    MessageBox.Show("Dit OLC nummer staat al in de lijst");
}

Switch statement?

+4
source share
1 answer

Another way would be to use a dictionary

//of course, the "staat al in de lijst" could be a constant, as we like DRY
var messageDictionary = new Dictionary<string, string>() {
   {"hnummer", "Deze laptop staat al in de lijst"},
   {"serienummmer", "Dit serienummer staat al in de lijst"}
}

then something like this (if you want several messages for each "successful" to contain a test, as your code shows).

foreach (var kvp in messageDictionary) {
      if (ex.Message.Contains(kvp.Key))
      Messagebox.Show(kvp.Value);
      //break; if you wanna stop after first match.
}

or if you want to test everything "contains", but get only one aggregated message

var res = string.Empty;
foreach (var kvp in messageDictionary) {
   if (ex.Message.Contains(kvp.Key))
          res +=kvp.Value;
}
MessageBox.Show(res);

or "don't do it" oneliner way

MessageBox.Show(string.Join("\n", messageDictionary.Select(m => ex.Message.Contains(m.Key) ? m.Value : string.Empty)));
+4
source

All Articles