Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the C# pattern to perform an action on a series of values?

Tags:

c#

I have this code:

if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Orange) == KeyState.Lock)
    PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Orange, 0, 0);

if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Blue) == KeyState.Lock)
    PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Blue, 0, 0);

if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Shift) == KeyState.Lock)
    PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Shift, 0, 0);

if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Control) == KeyState.Lock)
    PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Control, 0, 0);

...

and I want to refactor the code separating the key / function definition from the actions. Key.xxx and Function.xxx aren't from the same type.

eg: in Python, I could simply do something like:

keys = (
    ( Key.Orange, Function.Orange ),
    ( Key.Blue  , Function.Blue ),
    ( Key.Shift , Function.Shift ),
    ...
    )

psi_key = PsionTeklogix.Keyboard.Keyboard

for key, func in keys:
    if psi_key.GetModifierKeyState(key) == KeyState.Lock):
        psi_key.InjectKeyboardCommand(func, 0, 0)

What's "the right way" to do in C#?

like image 236
PabloG Avatar asked Aug 11 '10 18:08

PabloG


1 Answers

You can do something very similar:

Dictionary<Key, Function> keys = new Dictionary<Key, Function>
{
    { Key.Orange, Function.Orange },
    { Key.Blue, Function.Blue }
    ...
};

foreach (var pair in keys)
{
    if (Keyboard.GetModifierKeyState(pair.Key) == KeyState.Locked)
    {
        Keyboard.InjectKeyboardCommand(pair.Value, 0, 0);
    }
}

You could even use LINQ if you wanted to:

foreach (var pair in keys.Where(pair => 
                 Keyboard.GetModifierKeyState(pair.Key) == KeyState.Locked)
{
    Keyboard.InjectKeyboardCommand(pair.Value, 0, 0);
}

Now using a Dictionary is somewhat odd here given that we're not looking anything up. If you're using .NET 4 you could use a list of tuples instead:

var keys = new List<Tuple<Key, Function>>()
{
    Tuple.Of(Key.Orange, Function.Orange),
    Tuple.Of(Key.Blue, Function.Blue),
    ...
};

and adjust the loop accordingly. You could use an anonymous type, too:

var keys = new[]
{
    new { Key = Key.Orange, Function = Function.Orange },
    new { Key = Key.Blue, Function = Function.Blue },
    ...
};

They're all basically acting as ways of representing key/function pairs :)

like image 146
Jon Skeet Avatar answered Oct 03 '22 14:10

Jon Skeet