我有一个数组列表,我需要能够点击一个按钮然后从列表中随机挑选一个字符串并显示在消息框中。

我该怎么做呢?


当前回答

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 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();

如果你只有一个数组列表,你可以强制转换它:

var strings = myArrayList.Cast<string>();

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 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>或数组。

ArrayList ar = new ArrayList();
        ar.Add(1);
        ar.Add(5);
        ar.Add(25);
        ar.Add(37);
        ar.Add(6);
        ar.Add(11);
        ar.Add(35);
        Random r = new Random();
        int index = r.Next(0,ar.Count-1);
        MessageBox.Show(ar[index].ToString());

我已经使用这个ExtensionMethod一段时间了:

public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
{
    if (count <= 0)
      yield break;
    var r = new Random();
    int limit = (count * 10);
    foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
      yield return item;
}