如何从列表中获取随机数的元素

时间:2016-03-28 10:37:22

标签: c# list random

我正在给你写一个小问题。我在C#.NET MVC5中编写小应用程序,我有一个问题,如何从List中获取一些随机项?

我的代码:

public ActionResult ProductsList()
{
    List<Product> products = productRepo.GetProduct().ToList();
    return PartialView(products);
}

此方法返回完整列表,如何正确执行?

4 个答案:

答案 0 :(得分:3)

我建议选择随机索引,然后返回相应的项目:

// Simplest, not thread-safe
private static Random s_Random = new Random();

private static List<Product> PartialView(List<Product> products, int count = 6) {
  // Too few items: return entire list
  if (count >= products.Count)
    return products.ToList(); // Let's return a copy, not list itself

  HashSet<int> taken = new HashSet<int>();

  while (taken.Count < count)
    taken.Add(s_Random.Next(count));

  List<Product> result = new List<Product>(count);

  // OrderBy - in case you want the initial order preserved
  foreach (var index in taken.OrderBy(item => item))
    result.Add(products[index]);

  return result;
}

答案 1 :(得分:1)

生成一个随机的no,并根据生成的随机数获取列表中的6个元素。

    public ActionResult ProductsList()
    {
        Random rnd = new Random();
        List<Product> products = productRepo.GetProduct().ToList();
        Random r = new Random();
        int randomNo = r.Next(1, products.Count);
        int itemsRequired = 6; 
        if (products.Count <= itemsRequired)
            return PartialView(products));
        else if (products.Count - randomNo >= itemsRequired)
            products = products.Skip(randomNo).Take(itemsRequired).ToList();
        else
            products = products.Skip(products.Count - randomNo).Take(itemsRequired).ToList();
        return PartialView(products));

答案 2 :(得分:1)

在某处创建Random类的实例。请注意,每次需要随机数时都不要创建新实例非常重要。您应该重用旧实例以实现生成数字的一致性。

static Random rnd = new Random();
List<Product> products = productRepo.GetProduct().ToList();
int r = rnd.Next(products.Count);
products = products.Take(r).ToList();

答案 3 :(得分:0)

使用Random类并使用NEXT函数返回指定限制以下的非负数...

List<Product> products = productRepo.GetProduct().ToList();

var randomProduct=new Random();

var index=randomProduct.Next(products.Count);

return PartialView(products[index]);

希望这可以帮到你.. 快乐的编码