0

我正在尝试访问列表中随机元素的值。目前我的代码似乎返回的是元素而不是值。

int x = _randMoveDecider.Count;

//makes sure x is never more than the array size
if(x != 0)
  {
    x = x - 1 ;
  }

Random _r = new Random();

_move = _r.Next(_randMoveDecider[x]);

return _randMoveDecider[_move];

目前,如果 _randMoveDecider 持有值 2、5 和 9,它将返回 0、1 或 2 而不是列表中的值,我哪里出错了?

[编辑] 我想我应该说,_randMoveDecider 的长度和存储在其中的值随着程序的每次运行而变化,但它们始终是整数。

4

4 回答 4

3

就这个怎么样?

// as a field somewhere so it's initialised once only
public Random _r = new Random();

    // later in your code
var _randList = new List<int>{4,5,8,9};
var _move = _r.Next(_randList.Count);
return _randList[_move];

更好的是,这里有一些可以随机化任何列表的东西:

public static Random _rand = new Random();

public IEnumerable<T> Randomise<T>(IList<T> list)
{
    while(true)
    {
        // we find count every time since list can change
        // between iterations
        yield return list[_rand.Next(list.Count)];
    }
}

在您的场景中使用它的一种方法:

// make this a field or something global
public IEnumerbale<int> randomiser = Randomise(_randList);

// then later
return randomiser.First();
于 2012-05-01T05:42:49.053 回答
2

首先,您应该初始化 Random 一次。使其成为一个字段:

private Random _rand = new Random();

然后从适当的范围内得到一个随机数。if(x!=0) 没用 - Next() 返回 numbersform <0, n) 范围

return _randMoveDecider[_rand.Next(_randMoveDecider.Count)];
于 2012-05-01T05:42:33.403 回答
1

只需在主类中添加这个扩展类:

public static class Extensions
{
    public static int randomOne(this List<int> theList)
    {
        Random rand = new Random(DateTime.Now.Millisecond);
        return theList[rand.Next(0, theList.Count)];
    }
}

然后调用它:

int value = mylist.randomOne();

编辑:这是一个测试程序,演示如何使用该方法。请注意,由于 Random 的错误使用,它会产生非常不平衡的结果,100 个中超过 50 个“随机”数字是相同的。

class Program
{
    static void Main(string[] args)
    {
        var myList = Enumerable.Range(0, 100).ToList();
        var myRandoms = myList.Select(v => new { key = v, value = 0 })
                 .ToDictionary(e => e.key, e => e.value);

        for (int i = 0; i < 100; i++)
        {
            var random = myList.RandomOne();
            myRandoms[random]++;
        }

        Console.WriteLine(myRandoms.Values.Max());
        Console.ReadLine();
    }
}

要解决此问题,请为 Extension 类制作 Random 静态实例或在程序中更广泛地共享。这在Random 的常见问题解答中进行了讨论。

public static class Extensions
{
    static Random rand = new Random();
    public static int randomOne(this List<int> theList)
    {
        return theList[rand.Next(0, theList.Count)];
    }
}
于 2012-05-01T06:11:34.950 回答
0
var random = new Random();
var item = list.ElementAt(random.Next(list.Count()));
于 2012-05-01T07:26:28.800 回答