ASP.NET MVC - How to get random records from model?
-
08-07-2019 - |
Question
I don't know if there is an easy way to do it but basically what I would like to do is:
var highlights = db.Banners.Where(h => h.Category == "highlight").ToList().GetRange(0,4);
I have this model Banners where I have some highlights but I would like to retrieve just 4 random highlights each time in different order.
So the code I'm using just retrieve a range from [0..4] highlights and if you have less than 4, it returns an error, and they are not randomised.
Any ideas on how could I do it easily?
The result I would like to have is a List<
Banner>
to pass it to the view but each time with different order like:
[1,3,4,2] || [2,1,4,3] || [12,32,15,3]
I think that's it :)
Thanks a lot
Solution
Here is an example of Random LINQ sampling on codeproject
OTHER TIPS
To randomize banners and get first four or less you could do this:
Random r = new Random(DateTime.Now.Ticks);
var highlights = db.Banners.Where(h => h.Category == "highlight").
OrderBy(h => r.Next()).Take(4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow