How to access random item in list?

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

    I usually use this little collection of extension methods:

    public static class EnumerableExtension
    {
        public static T PickRandom(this IEnumerable source)
        {
            return source.PickRandom(1).Single();
        }
    
        public static IEnumerable PickRandom(this IEnumerable source, int count)
        {
            return source.Shuffle().Take(count);
        }
    
        public static IEnumerable Shuffle(this IEnumerable source)
        {
            return source.OrderBy(x => Guid.NewGuid());
        }
    }
    

    For a strongly typed list, this would allow you to write:

    var strings = new List();
    var randomString = strings.PickRandom();
    

    If all you have is an ArrayList, you can cast it:

    var strings = myArrayList.Cast();
    

提交回复
热议问题