如何访问列表中的随机项目?

问题描述 投票:0回答:13

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

我该怎么做?

c# arrays string random
13个回答
483
投票
  1. 在某处创建

    Random
    类的实例。请注意,不要在每次需要随机数时都创建一个新实例,这一点非常重要。您应该重用旧实例以实现生成的数字的一致性。你可以在某处有一个
    static
    字段(注意线程安全问题):

    static Random rnd = new Random();
    
  2. 要求

    Random
    实例为您提供一个随机数,其中
    ArrayList
    中的项目数最大:

    int r = rnd.Next(list.Count);
    
  3. 显示字符串:

    MessageBox.Show((string)list[r]);
    

161
投票

我通常使用这个扩展方法的小集合:

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

105
投票

你可以这样做:

list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()

33
投票

或者像这样的简单扩展类:

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>
等索引集合或数组。


28
投票

创建一个

Random
实例:

Random rnd = new Random();

获取随机字符串:

string s = arraylist[rnd.Next(arraylist.Count)];

但请记住,如果您经常这样做,您应该重复使用

Random
对象。将其作为类中的静态字段,以便仅初始化一次,然后访问它。


6
投票

我会建议不同的方法,如果列表中项目的顺序在提取时并不重要(每个项目只应选择一次),那么您可以使用

List
代替 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
将尝试从无序集合中提取“随机”对象。


5
投票

为什么不:

public static T GetRandom<T>(this IEnumerable<T> list)
{
   return list.ElementAt(new Random(DateTime.Now.Millisecond).Next(list.Count()));
}

3
投票
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());

2
投票

我已经使用这个扩展方法有一段时间了:

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;
}

1
投票

我需要更多的物品,而不仅仅是一件。所以,我写了这个:

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

1
投票

从 JSON 文件中随机打印国家/地区名称。
型号:

public class Country
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }

实施:

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

0
投票

.NET8 显着改进了这一点:

string[] stringArray = ["first","second","third"];

string rndItem = Random.Shared.GetItems(stringArray, 1)[0];

-3
投票

为什么不[2]:

public static T GetRandom<T>(this List<T> list)
{
     return list[(int)(DateTime.Now.Ticks%list.Count)];
}
© www.soinside.com 2019 - 2024. All rights reserved.