I wonder if there is any helper class in the .NET framework (or somewhere else) that converts chars to ConsoleKey enums.
e.g 'A' should become ConsoleKey.A
Before someone asks why I would want to do that. I want to write a helper that takes a string (e.g. 'Hello World') and converts it into a sequence of ConsoleKeyInfo objects. I need this for some crazy unit tests where I'm mocking user input.
I'm just a little tired of creating glue code on my own so I thought, maybe there is already a way to convert a char to a ConsoleKey enum?
For completeness here is what seems to work great so far
public static IEnumerable<ConsoleKeyInfo> ToInputSequence(this string text)
{
return text.Select(c =>
{
ConsoleKey consoleKey;
if (Enum.TryParse(c.ToString(CultureInfo.InvariantCulture), true, out consoleKey))
{
return new ConsoleKeyInfo(c, consoleKey, false, false, false);
}
else if (c == ' ')
return new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
return (ConsoleKeyInfo?) null;
})
.Where(info => info.HasValue)
.Select(info => info.GetValueOrDefault());
}
Have you tried:
char a = 'A';
ConsoleKey ck;
Enum.TryParse<ConsoleKey>(a.ToString(), out ck);
So:
string input = "Hello World";
input.Select(c => (ConsoleKey)Enum.Parse(c.ToString().ToUpper(), typeof(ConsoleKey));
or
.Select(c =>
{
return Enum.TryParse<ConsoleKey>(a.ToString().ToUpper(), out ck) ?
ck :
(ConsoleKey?)null;
})
.Where(x => x.HasValue) // where parse has worked
.Select(x => x.Value);
Also Enum.TryParse() has an overload to ignore case.
If you using .NET4 or later you can use Enum.TryParse. and Enum.Parse is avalable for .NET2 and later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With