Reverse Switch Statement

I want to change the code inside the switch block, doing it myself (it seems to me that this does not make sense) for example:

{ string name = Console.ReadLine(); string s = null; for (int i = 0; i < name.Length; i++) { switch (name[i]) { case 'a': s += '1';break; case 'q': s += '2'; break; } } } 

How to make it reverse to act as follows:

  case '1': s += 'a';break; case '2': s += 'q'; break; 

My code contains more than 30 statements for each character.

+6
source share
3 answers

Create a Dictionary<char, char> for matching (in fact, you can create two for reasons of performance and ease of use) or a simple list type with a custom object (for example, List<Tuple<char, char>> ). You can make a way to simplify the addition. Please note that key and val must be unique!

 private void Add(char key, char val, Dictionary<char, char> dictionary, Dictionary<char, char> reverseDictionary) { dictionary.Add(key, val); reverseDictionary.Add(val, key); } 

Then use this:

 Dictionary<char, char> dictionary = new Dictionary<char, char>(); Dictionary<char, char> reverseDictionary = new Dictionary<char, char>(); this.Add('a', '1', dictionary, reverseDictionary); ... char outputChar; if (dictionary.TryGetValue(inputChar, out outputChar)) { // use outputChar } 

And for the opposite:

 char outputChar; if (reverseDictionary.TryGetValue(inputChar, out outputChar)) { // use outputChar } 
+2
source

You want something like this:

 var dictionary = new Dictionary<char, char> {{'1', 'a'}, {'2', 'q'} /* ... */ }; string name = Console.ReadLine(); string s = name.Where(dictionary.ContainsKey) .Aggregate("", (current, t) => current + dictionary[t]); Console.WriteLine(s); 

Entering 12 will return aq . You can also change it:

 string s = name.Where(dictionary.ContainsValue) .Aggregate("", (current, t) => current + dictionary.FirstOrDefault(z => z.Value == t).Key); 

So, now you can look at the value and get the key. So entering aq will return 12 .

+1
source

One option is to create a dictionary to store the match, and then loop through the match to create the output string if the current character exists in the match dictionary.

The solution below shows the use of a dictionary of case-insensitive strings, so you don't need to have multiple entries for upper and lower case (this is obviously an optional design).

I also show the use of StringBuilder, which is much more efficient when adding strings.

 var MappingDictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); MappingDictionary.Add("1", "a"); MappingDictionary.Add("2", "q"); var name = Console.ReadLine(); if (!string.IsNullOrEmpty(name)) { var s = new StringBuilder(500); foreach (var sourceChar in name) { string mappedTo; if (MappingDictionary.TryGetValue(sourceChar.ToString(), out mappedTo)) { s.Append(mappedTo); } } } 
0
source

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


All Articles