Meh*_*ari 384
在Random某处创建一个类的实例.请注意,每次需要随机数时都不要创建新实例.您应该重用旧实例以实现生成数字的一致性.你可以在static某个地方有一个字段(小心线程安全问题):
static Random rnd = new Random();
要求Random实例为您提供一个随机数,其中包含以下项中最大项数ArrayList:
int r = rnd.Next(list.Count);
显示字符串:
MessageBox.Show((string)list[r]);
Mar*_*ann 129
我通常使用这个小扩展方法集合:
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());
    }
}
对于强类型列表,这将允许您编写:
var strings = new List<string>();
var randomString = strings.PickRandom();
如果您拥有的只是一个ArrayList,则可以将其强制转换:
var strings = myArrayList.Cast<string>();
Fel*_*oto 87
你可以做:
list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()
Joe*_*oey 20
创建一个Random实例:
Random rnd = new Random();
获取随机字符串:
string s = arraylist[rnd.Next(arraylist.Count)];
但请记住,如果经常这样做,则应重新使用该Random对象.将它作为一个静态字段放在类中,这样它只被初始化一次然后访问它.
Dav*_*_cz 16
或者像这样的简单扩展类:
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>为此目的使用索引集合或数组.
我会建议不同的方法,如果列表中项目的顺序在提取时并不重要(并且每个项目只应选择一次),那么List您可以使用 a来代替 a ConcurrentBag,它是线程安全的、无序的集合对象:
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 T GetRandom<T>(this IEnumerable<T> list)
{
   return list.ElementAt(new Random(DateTime.Now.Millisecond).Next(list.Count()));
}