Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Posts Tagged ‘map command’

How to map a command to method without using if/switch?

Posted by Paul on November 26, 2010

Here I am trying to show the advantage of using Lambda expressions along with some built in delegates.


The user will input a command like “MoveUp”, “MoveDown”, “TurnLeft”, “TurnDown”.  Based on the commands, you have to call the the methods MoveUp(), MoveDown(), TurnLeft(), TurnDown() respectively.

The old code will look like:

string command = "Move";


if (command == "MoveUp")


else if (command == "MoveDown")


else if (command == "TurnLeft")


else if (command == "TurnRight")


We can replace the same code with Lambda and built-in delegate Action as:

string command = "Move";


IDictionary<string, Action> actions = new Dictionary<string, Action>();

actions.Add("MoveUp", MoveUp);

actions.Add("MoveDown", MoveDown);

actions.Add("TurnLeft", TurnLeft);

actions.Add("TurnRight", TurnRight);


actions.Where(a => a.Key == command).FirstOrDefault().Value();

Note: The Action is a built-in delegate with void as return and no arguments input.  There are total of 4 versions of Action.


Posted in Lambda Expressions | Tagged: , , , | Leave a Comment »