How to access random item in list?

后端 未结 12 1079
滥情空心
滥情空心 2020-11-22 15:20

I have an ArrayList, and I need to be able to click a button and then randomly pick out a string from that list and display it in a messagebox.

How would I go about

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 15:37

    ArrayList ar = new ArrayList();
            ar.Add(1);
            ar.Add(5);
            ar.Add(25);
            ar.Add(37);
            ar.Add(6);
            ar.Add(11);
            ar.Add(35);
            Random r = new Random();
            int index = r.Next(0,ar.Count-1);
            MessageBox.Show(ar[index].ToString());
    

提交回复
热议问题