Reputation: 341
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?
Upvotes: 0
Views: 554
Reputation: 1210
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();
Upvotes: 1
Reputation: 4423
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));
Upvotes: 1
Reputation: 186688
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;
}
Upvotes: 3
Reputation: 1
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
Upvotes: 0