0

I have a list of methods, and I want to select a random method from the list and execute it while a boolean is set to true. I have:

 List<Action> myActions = new List<Action>();

 public void SetupRobot()
 {               
    myActions.Add(mRobot.turnLeft);
    myActions.Add(mRobot.turnRight);
    myActions.Add(mRobot.move);
 }


 private void randomDemo()
    {
        while (mRandomActive)
        {           
                foreach (Action aAction in myActions)
                {
                    //randomly method and execute
                    Random rndm = new Random();
                }
        }
    }

Unsure as to how I would select the method from the list with object rndm

Scott
  • 1,806
  • 1
  • 23
  • 41

2 Answers2

3
private void randomDemo()
{
    Random r = new Random();
    while (mRandomActive)
    {           
        int index = r.Next(myActions.Count);
        var action = myActions[index];
        action();
    }
}
Zbigniew
  • 26,284
  • 6
  • 55
  • 64
  • also to add to the answer: a more [elegant but expensive](http://stackoverflow.com/questions/2019417/access-random-item-in-list#2019433) solution – Manish Mishra May 02 '13 at 08:57
  • Yes, turning `Random` into class variable could be a good idea, especially if you are keep executing `randomDemo()` method. – Zbigniew May 02 '13 at 08:59
1
Random rndm = new Random();    
while (mRandomActive){
    //randomly method and execute
    var index = rndm.Next(myActions.Count);
    myActions[index]();
}
Omar
  • 15,543
  • 9
  • 43
  • 64
Raphaël Althaus
  • 58,557
  • 6
  • 89
  • 116