2016-03-28 73 views
0

我正在写给你一个小问题。我在C#.NET MVC5中编写小应用程序,我有一个问题,我如何从列表中获得一些随机项目?我如何从列表中获得随机数的元素

我的代码:

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

这个方法返回完整列表,我该怎么做是正确的?

+0

什么是少数,2或3或特定的任何数字? –

+0

请详细说明*一些随机项*。例如,你允许*重复*吗? :'列表[3],列表[7],列表[3]'?这些项目是否应该*订购*:'列表[3],列表[8]'或者列表[8],列表[3]'也可以做到这一点? –

+0

6个项目可以很好,无需重复 – Giacomo

回答

1

根据生成的随机数生成一个随机数并获取列表的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)); 
+0

我该如何做最小和最大数量的随机元素?现在它给了我随机数量的元素。我需要6个元素默认,总是。 – Giacomo

+1

@Giacomo,我已经更新了我的答案,以便始终生成6个元素。 –

+0

如果最初的产品列表有*值太少,该怎么办?例如。只有'itemsRequired = 6'时才有'3'?在你当前的代码中,一个* exception *将被抛出,当最好的出路,恕我直言,是返回整个列表。 –

1

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

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

我很确定这将始终从列表的开始。 – Derek

+0

如果'rnd.Next(list.Count)'返回* zero *会怎么样?可能,* emply列表*不是所需的输出。 –

0

利用Random类的,并利用其返回非负数低于指定限度NEXT功能...

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

var randomProduct=new Random(); 

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

return PartialView(products[index]); 

希望这可以帮助你.. 编码愉快

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