我有一个数组列表,我需要能够点击一个按钮然后从列表中随机挑选一个字符串并显示在消息框中。
我该怎么做呢?
我有一个数组列表,我需要能够点击一个按钮然后从列表中随机挑选一个字符串并显示在消息框中。
我该怎么做呢?
当前回答
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(); 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); Display the string: MessageBox.Show((string)list[r]);
其他回答
从JSON文件随机打印国家名称。 模型:
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);
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(); 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); Display the string: MessageBox.Show((string)list[r]);
我需要更多的项目,而不仅仅是一个。所以,我写了这个:
public static TList GetSelectedRandom<TList>(this TList list, int count)
where TList : IList, new()
{
var r = new Random();
var rList = new TList();
while (count > 0 && list.Count > 0)
{
var n = r.Next(0, list.Count);
var e = list[n];
rList.Add(e);
list.RemoveAt(n);
count--;
}
return rList;
}
有了这个,你可以像这样随机获取你想要的元素:
var _allItems = new List<TModel>()
{
// ...
// ...
// ...
}
var randomItemList = _allItems.GetSelectedRandom(10);
我将建议不同的方法,如果列表中项目的顺序在提取时并不重要(并且每个项目应该只选择一次),那么您可以使用ConcurrentBag,而不是list,它是线程安全的,无序的对象集合:
var bag = new ConcurrentBag<string>();
bag.Add("Foo");
bag.Add("Boo");
bag.Add("Zoo");
事件:
string result;
if (bag.TryTake(out result))
{
MessageBox.Show(result);
}
TryTake将尝试从无序集合中提取一个“随机”对象。
或者像这样简单的扩展类:
public static class CollectionExtension
{
private static Random rng = new Random();
public static T RandomElement<T>(this IList<T> list)
{
return list[rng.Next(list.Count)];
}
public static T RandomElement<T>(this T[] array)
{
return array[rng.Next(array.Length)];
}
}
然后只需呼叫:
myList.RandomElement();
也适用于数组。
我将避免调用OrderBy(),因为对于较大的集合来说,它的开销很大。为此,可以使用索引集合,如List<T>或数组。