How to select a random element from List

2019-09-12 17:16发布

问题:

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

回答1:

private void randomDemo()
{
    Random r = new Random();
    while (mRandomActive)
    {           
        int index = r.Next(myActions.Count);
        var action = myActions[index];
        action();
    }
}


回答2:

Random rndm = new Random();    
while (mRandomActive){
    //randomly method and execute
    var index = rndm.Next(myActions.Count);
    myActions[index]();
}