简体   繁体   中英

How can I get a random number of element from list

I am writing to You with small problem. I am writing small application in C#.NET MVC5, and I have one question, how can I get a few random items from List?

My code:

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

This method return full list, how can I do it correctly?

I suggest selecting out random indexes and then returning corresponding items:

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

Generate a random no and fetch the 6 elements of the list based on the random No. generated.

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

Create an instance of Random class 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.

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

Make use of the Random class and make use of NEXT function which returns the non negative number below the specified limit...

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

var randomProduct=new Random();

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

return PartialView(products[index]);

Hope this could help you.. Happy coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM