What is the best (and fastest) way to retrieve a random row using Linq to SQL when I have a condition, e.g. some field must be true?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I have random function query against
DataTable
s:You can do this at the database, by using a fake UDF; in a partial class, add a method to the data context:
Then just
order by ctx.Random()
; this will do a random ordering at the SQL-Server courtesy ofNEWID()
. i.e.Note that this is only suitable for small-to-mid-size tables; for huge tables, it will have a performance impact at the server, and it will be more efficient to find the number of rows (
Count
), then pick one at random (Skip/First
).for count approach:
The example below will call the source to retrieve a count and then apply a skip expression on the source with a number between 0 and n. The second method will apply order by using the random object (which will order everything in memory) and select the number passed into the method call.
If you use LINQPad, switch to C# program mode and do this way:
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 partial query to access the table in random order is ...
This does an XOR operation in the database and orders by the results of that XOR.
Advantages:-
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.
if you want to get e.g.
var count = 16
random rows from table, you can writehere I used E.F, and the Table is a Dbset