Random Linq

First time programming in a while and realised that I needed a random row, In SQL (2005 onwards) thats fairly easy;

select top 4 * from table order by NewID()

however I’m not using SQL I’m using Linq..

the most basic solution is; count the rows, then get a random number in the range of the number of rows and return the row which matches the index.

var q = from r in db.TableBlobs
          select row;

int ncount = q.Count();
int nindex = new Random().Next(ncount);

Blobs blob = q.Skip(nindex).FirstOrDefault();

For a more advanced answer see here

Leave a Reply

Your email address will not be published. Required fields are marked *