如何从列表中获取随机项目 [英] How to get a random item from a List

查看:89
本文介绍了如何从列表中获取随机项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天 我有这个数组和列表,我想从列表中获取一个随机值

Good day I have this array and list and i would like to get a random value from the list

random Ram = new Random();
String[] Test= {"C2", "C3", "C4"};

List<String> LTest = new List<String>(Test);

String var = Ram.Next(LTest);

错误-无法从system.collection.generic.list转换为'Int'

Error -cannot convert from system.collection.generic.list to 'Int'

我也想继续从列表中删除该对象并将其添加到新对象中

and also i would like to continue to remove the object from the list and add it to a new one

Test.remove(Var);

newlist.add(Var);

谢谢.

推荐答案

如果您想从列表中随机选择一个项目,则可以采用几种方法.

If you want to choose an item from the list at random, you can do it a couple ways.

您可以使用random来计算整数,并将其用作索引:

You can use random to compute an integer, and use that as an index:

var index = random.Next(list.Count);
var randomItem = list[index];

或者您可以将列表随机排序并采用第一个:

Or you can just sort the list randomly and take the first one:

var item = list.OrderBy( s => random.NextDouble() ).First();

第一种方法很常见;如果您希望从列表中选择多个随机项目,并且希望避免重复,则第二种方法很方便.只需拿第一,第二,第三等项目.

The first method is very common; the second method is handy if you expect to be picking more than one random item from the list and you wish to avoid repetition. Just take the first, second, third, etc. items.

这篇关于如何从列表中获取随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆