我有一个数组列表,我需要能够点击一个按钮然后从列表中随机挑选一个字符串并显示在消息框中。
我该怎么做呢?
我有一个数组列表,我需要能够点击一个按钮然后从列表中随机挑选一个字符串并显示在消息框中。
我该怎么做呢?
当前回答
创建一个随机实例:
Random rnd = new Random();
获取一个随机字符串:
string s = arraylist[rnd.Next(arraylist.Count)];
记住,如果你经常这样做,你应该重用随机对象。将它作为类中的静态字段,这样它只初始化一次,然后访问它。
其他回答
为什么不:
public static T GetRandom<T>(this IEnumerable<T> list)
{
return list.ElementAt(new Random(DateTime.Now.Millisecond).Next(list.Count()));
}
为什么不[2]:
public static T GetRandom<T>(this List<T> list)
{
return list[(int)(DateTime.Now.Ticks%list.Count)];
}
我将建议不同的方法,如果列表中项目的顺序在提取时并不重要(并且每个项目应该只选择一次),那么您可以使用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将尝试从无序集合中提取一个“随机”对象。
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]);
你可以:
list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()