7

I want to reverse the code inside switch block rather doing it my self (it seems to make no sense to me) ex:

{            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 reversed to act like this:

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

My code contains more than 30 statements for each character.

3
  • 4
    1. Create a Dictionary. 2. ??????? 3. PROFIT!!!!11 Commented Jan 13, 2015 at 23:23
  • 1
    This is good because you realized there must be a better way. Commented Jan 13, 2015 at 23:25
  • 2
    doing it with a switch in the first place was wrong. You should have a pair of char arrays that map from one to the other Commented Jan 13, 2015 at 23:25

3 Answers 3

2

Create a Dictionary<char, char> for the mapping (in fact you could create two for performance reasons and ease of use), or a simple list type with a custom object (like List<Tuple<char, char>>). You could make a method to make adding easier. 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 reverse:

char outputChar;
if (reverseDictionary.TryGetValue(inputChar, out outputChar))
{
    // use outputChar
}
Sign up to request clarification or add additional context in comments.

4 Comments

oops, I'm still beginner and that code seems to be unfamiliar to me, but thanks very much, it still looks like very simple than duplicating switch statement!
What is unclear? I guess lambda expressions are a bridge too far for you ;)
Lol. What the code does is 1. set up a dictionary; 2. get the value from the dictionary for a specific key. The things you need to do it bind that together with your current code.
Actually I duplicated the code! Seems that this is the only way I can understand. I'll remember your code wile I progress in learning C#
1

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

Typing 12 will return aq. You can also reverse it:

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

So now you can look up by value and get key. So typing aq will return 12.

Comments

0

One option is to create a dictionary to hold the mapping and then loop through the mapping building up the output string if the current character exists in the mapping dictionary.

The solution below shows using a dictionary of strings that ignore case and culture so that you don't have to have multiple entries for upper and lower case (this is obviously an optional design).

I am also showing the use of StringBuilder, which is far more efficient when appending 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);
        }
    }
}

Comments