views:

236

answers:

2

Hello there, 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

A: 

Here is an example of Random LINQ sampling on codeproject

Best of luck,

Dan

Daniel Elliott
-1, the code you linked to extracts the entire IEnumerable into a list first - this would mean loading the entire DB table into memory in order to choose 4 random ones.
orip
On second thought, he loads all the highlights into memory anyway. I can't seem to undo the '-1', though, sorry.
orip
Thats very good Dan! I agree with orip, but the thing is that at least for now it's working pretty well since I have just few records in the database it won't be such a problem.
ludicco
Without randomizing the SQL, I don't know how would you get 4 random from whole set without loading the whole set?
Daniel Elliott
+2  A: 

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)
Alexander Prokofyev
That's nice Alexander, thanks a lot. but the problem here is that the order is always the same like [2,3,4,5] || [1,2,3,4]I think in my case would be nice to have them different and mixed each time. :)
ludicco
Well, you should use random seed based on timer when creating Random object.
Alexander Prokofyev
I have changed the code a bit. Check it.
Alexander Prokofyev