How to access random item in list?

后端 未结 12 1103
滥情空心
滥情空心 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:58

    Create a Random instance:

    Random rnd = new Random();
    

    Fetch a random string:

    string s = arraylist[rnd.Next(arraylist.Count)];
    

    Remember though, that if you do this frequently you should re-use the Random object. Put it as a static field in the class so it's initialized only once and then access it.

提交回复
热议问题