-1

I'm sorry if the title is wrong I didnt know how is called what I want to do.

Im starting in C# (Python is my strong).

The thing that I want to do in C# is, I dont know how to explain, but I will put how you can do it in python.

I want to show different message depends of the action, but I not want use a lot of If's.

Right now in C# I have a textBox with the KeyDow event, so if I press number I want that show "You pressed a number" but if I press a dot (.) it will tell me "You pressed a dot".

in python I would do like that:

def keyDownEvent(self, k):
    if k.key.text in [1,2,3,4,5,6,7,8,9,0]:
        print(f"You pressed {k.key.text}")
    else:
        print("You pressed " + {"decimal": "dot", "OemPeriod": "dot"}[k.key.text])

this is a example how I would do in python, and inside of this temporary dictionary I can put more stuffs..

how I can do something like that in C#?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Jess Jss
  • 25
  • 6
  • One possibility would be to use a `switch` - `case`. – MSeifert Jan 26 '19 at 15:33
  • new Dictionary(){"decimal": "dot", etc}[k.key.text] – Rory Jan 26 '19 at 15:36
  • You are looking for a map from key char to name essentiallly? . -> "Dot", , -> "Comma", ...? You OK with 1 -> "Number", 2-> "Number", or must it be 1,2,3,4 -> "Number"? – Mirko Jan 26 '19 at 15:37
  • Possible duplicate of https://stackoverflow.com/questions/3164998/is-there-a-c-sharp-in-operator – Kevin Gosse Jan 26 '19 at 15:38
  • @KevinGosse I not want check if the string contains a character, I want that depend the key, show a Message but without use a lot of if's – Jess Jss Jan 26 '19 at 15:42
  • @JessJss That other question is about finding an equivalent in C# to the `in` operator (OP uses SQL as an example, but that's really the same one as in Python), so I fail to see the difference with your example – Kevin Gosse Jan 26 '19 at 15:45
  • For exemple, this answer: https://stackoverflow.com/a/3165188/869621 would allow you to write `if (k.key.text.In(1,2,3,4,5,6,7,8,9,0))`. Isn't that what you want? – Kevin Gosse Jan 26 '19 at 15:47

3 Answers3

1

You can use a switch case.

var keyChar = Convert.ToChar(e.KeyValue); 

switch (keyChar)
{
   case var _ when new []{'1','2','3','4','5','6','7','8','9','0' }.Contains(keyChar):
      // Its a number, Show message in Text/MessageBox
      break;
   case var _ when keyChar.Equals("."):
      // Its a Dot, Show message in Text/MessageBox
      break;
//so on....
}

Do note that the first case (numbers) could be matched with Regular Expression as well. You could rewrite the first case as.

case var _ when Regex.IsMatch(keyChar.ToString(), @"\d"):

Please note it isn't quite necessary to convert to char (first line). You can writ the switch on KeyCode as well( in which case, the conditions needs to be based on the System.Windows.Form.Keys enum).

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
0

Just threw together some quick options based on what I thought you might be after. (This is just a console app so you can try it quickly):

Edit: Changed to make mapping portion more obvious for question from infrastructural "stuff":

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var done = false;

            Console.WriteLine("Press Q to Exit");
            while (!done)
            {
                var key = GrabUpperKey();

                var mapped1 = MapPlain(key);
                var mapped2 = MapRegexDynamic(key);
                var mapped3 = MapRegexConditional(key);

                Console.WriteLine($"You typed a {mapped1}, {mapped2}, {mapped3}");
                done = key == "Q";
            }
        }

        private static string MapRegexConditional(string key)
        {
            if (Regex.IsMatch(key, "^[0-9]$"))
            {
                return "Number";
            }

            if (Regex.IsMatch(key, @"^[\.]$"))
            {
                return "Dot";
            }

            if (Regex.IsMatch(key, @"^[A-Z]$"))
            {
                return "Letter";
            }

            return "N/A";
        }

        private static string MapRegexDynamic(string key)
        {
            var mappings = new Dictionary<string, string>()
            {
                { "^\\.$", "Dot" },
                { "^[0-9]$", "Number" },
                { "^[A-Z]$", "Letter" }
            };

            var firstMatch = mappings
                .Where(mapping => Regex.IsMatch(key.ToString(), mapping.Key))
                .Select(mapping => mapping.Value)
                .FirstOrDefault();

            return firstMatch ?? "N/A";
        }

        private static string MapPlain(string key)
        {
            var mapping = new Dictionary<string, string>()
            {
                { ".", "Dot" },
                { "0", "Number" },
                { "1", "Number" },
                { "2", "Number" },
                { "3", "Number" },
                { "4", "Number" },
                { "5", "Number" },
                { "6", "Number" },
                { "7", "Number" },
                { "8", "Number" },
                { "9", "Number" },
                { "A", "Letter" },
                { "Q", "Letter" }
            };

            return !mapping.ContainsKey(key) ? "N/A" : mapping[key];
        }

        private static string GrabUpperKey()
        {
            return Console.ReadKey().KeyChar.ToString().ToUpperInvariant(); // Just doing this to not have to handle upper and lower chars
        }
    }
}
Mirko
  • 4,284
  • 1
  • 22
  • 19
  • Thanks so much. I did like that answer. And the Regex features... u went to far, that's awesome, I never thought in do regex. Thanks so much. – Jess Jss Jan 26 '19 at 16:20
  • Was just gonna update this to make the mapping portion more obvious. Let me change it and you let me know if you like the old or new better. – Mirko Jan 26 '19 at 16:21
  • My personal preference is probably MapRegexDynamic, but of course depends on use-case – Mirko Jan 26 '19 at 16:23
-1

With the linq method Contains you get someting similar.

var value = int.Parse(Console.ReadLine());
if (new List<int> { 1, 2, 3, 4, 5 }.Contains(value))
    {
        Console.WriteLine("You clicked " + value);
    }