How to access random item in list?

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

    I have been using this ExtensionMethod for a while:

    public static IEnumerable GetRandom(this IEnumerable list, int count)
    {
        if (count <= 0)
          yield break;
        var r = new Random();
        int limit = (count * 10);
        foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
          yield return item;
    }
    

提交回复
热议问题