Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Orderby random ThreadSafe for use in ASP.NET

i'm using Asp.net MVC with Sharp Architecture.

I have this code:

return _repositoryKeyWord.FindAll(x => x.Category.Id == idCAtegory)
                .Take(50).ToList();

How can i order by random? Note: i don't want to order the 50 extracted items, i want order before and then extract 50 items.

thks

like image 963
Marco Casiraghi Avatar asked Jul 26 '10 21:07

Marco Casiraghi


2 Answers

One way to achieve efficiently is to add a column to your data Shuffle that is populated with a random int (as each record is created).

The query to access the table then becomes ...

Random random = new Random();
int seed = random.Next();
result = result.OrderBy(s => (~(s.Shuffle & seed)) & (s.Shuffle | seed)); // ^ seed);

This does an XOR operation in the database and orders by the results of that XOR.

Advantages:-

  1. Efficient: SQL handles the ordering, no need to fetch the whole table
  2. Repeatable: (good for testing) - can use the same random seed to generate the same random order
  3. Works on most (all?) Entity Framework supported databases

This is the approach used by my home automation system to randomize playlists. It picks a new seed each day giving a consistent order during the day (allowing easy pause / resume capabilities) but a fresh look at each playlist each new day.

like image 197
Ian Mercer Avatar answered Oct 22 '22 12:10

Ian Mercer


You can do this in T-Sql as described here. I don't think you can do it in linq without loading the whole result set into memory and then throwing most of it away, which you do not want to do.

like image 26
Gabe Moothart Avatar answered Oct 22 '22 13:10

Gabe Moothart