How to access random item in list?

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

    Printing randomly country name from JSON file.
    Model:

    public class Country
        {
            public string Name { get; set; }
            public string Code { get; set; }
        }
    

    Implementaton:

    string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
                string _countryJson = File.ReadAllText(filePath);
                var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);
    
    
                int index = random.Next(_country.Count);
                Console.WriteLine(_country[index].Name);
    
    0 讨论(0)
  • 2020-11-22 15:50

    Why not[2]:

    public static T GetRandom<T>(this List<T> list)
    {
         return list[(int)(DateTime.Now.Ticks%list.Count)];
    }
    
    0 讨论(0)
  • 2020-11-22 15:51
    1. Create an instance of Random class somewhere. Note that it's pretty important not to create a new instance each time you need a random number. You should reuse the old instance to achieve uniformity in the generated numbers. You can have a static field somewhere (be careful about thread safety issues):

      static Random rnd = new Random();
      
    2. Ask the Random instance to give you a random number with the maximum of the number of items in the ArrayList:

      int r = rnd.Next(list.Count);
      
    3. Display the string:

      MessageBox.Show((string)list[r]);
      
    0 讨论(0)
  • 2020-11-22 15:51

    I usually use this little collection of extension methods:

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

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

    var strings = new List<string>();
    var randomString = strings.PickRandom();
    

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

    var strings = myArrayList.Cast<string>();
    
    0 讨论(0)
  • 2020-11-22 15:53

    You can do:

    list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题