How to access random item in list?

后端 未结 12 1105
滥情空心
滥情空心 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>(_countryJson);
    
    
                int index = random.Next(_country.Count);
                Console.WriteLine(_country[index].Name);
    

提交回复
热议问题