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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2019417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:43:39  来源:igfitidea点击:

How to access random item in list?

c#arraysstringrandom

提问by jay_t55

I have an ArrayList, and I need to be able to click a button and then randomly pick out a string from that list and display it in a messagebox.

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

How would I go about doing this?

我该怎么做呢?

采纳答案by Mehrdad Afshari

  1. Create an instance of Randomclass 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 staticfield somewhere (be careful about thread safety issues):

    static Random rnd = new Random();
    
  2. Ask the Randominstance to give you a random number with the maximum of the number of items in the ArrayList:

    int r = rnd.Next(list.Count);
    
  3. Display the string:

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

    static Random rnd = new Random();
    
  2. 要求Random实例为您提供一个随机数,其中包含 中项目数的最大值ArrayList

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

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

回答by Joey

Create a Randominstance:

创建Random实例:

Random rnd = new Random();

Fetch a random string:

获取随机字符串:

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

Remember though, that if you do this frequently you should re-use the Randomobject. Put it as a static field in the class so it's initialized only once and then access it.

但请记住,如果您经常这样做,您应该重新使用该Random对象。将它作为类中的静态字段,这样它只初始化一次,然后访问它。

回答by Mark Seemann

I usually use this little collection of extension methods:

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

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

For a strongly typed list, this would allow you to write:

对于强类型列表,这将允许您编写:

var strings = new List<string>();
var randomString = strings.PickRandom();

If all you have is an ArrayList, you can cast it:

如果你只有一个 ArrayList,你可以投射它:

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

回答by Felipe Fujiy Pessoto

You can do:

你可以做:

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

回答by Rajesh Varma

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

回答by Dave_cz

Or simple extension class like this:

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

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

Then just call:

然后只需调用:

myList.RandomElement();

Works for arrays as well.

也适用于数组。

I would avoid calling OrderBy()as it can be expensive for larger collections. Use indexed collections like List<T>or arrays for this purpose.

我会避免打电话,OrderBy()因为对于较大的集合来说它可能很昂贵。List<T>为此目的使用索引集合,如或 数组。

回答by Carlos Toledo

I have been using this ExtensionMethod for a while:

我一直在使用这个 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;
}

回答by bafsar

I needed to more item instead of just one. So, I wrote this:

我需要更多的项目而不是一个。所以,我写了这个:

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

With this, you can get elements how many you want as randomly like this:

有了这个,你可以像这样随机获得你想要的元素数量:

var _allItems = new List<TModel>()
{
    // ...
    // ...
    // ...
}

var randomItemList = _allItems.GetSelectedRandom(10); 

回答by Lucas

Why not:

为什么不:

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

回答by Хидеки Матосува

Why not[2]:

为什么不[2]:

public static T GetRandom<T>(this List<T> list)
{
     return list[(int)(DateTime.Now.Ticks%list.Count)];
}