How to access random item in list?

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

    Or simple extension class like this:

    public static class CollectionExtension
    {
        private static Random rng = new Random();
    
        public static T RandomElement(this IList list)
        {
            return list[rng.Next(list.Count)];
        }
    
        public static T RandomElement(this T[] array)
        {
            return array[rng.Next(array.Length)];
        }
    }
    

    Then just call:

    myList.RandomElement();
    

    Works for arrays as well.

    I would avoid calling OrderBy() as it can be expensive for larger collections. Use indexed collections like List or arrays for this purpose.

提交回复
热议问题