Home

Getting random records from a table using LINQ to SQL

I needed to get a number of random records from a table and a quick google search led me to http://mosesyap.com/BlogWeb/post/2008/07/C-Getting-a-Random-Record-from-a-Table-inside-the-SQL-Server-Database.aspx This is a very quick and easy mechanism to use and will work on any table. To load a specific number of random records change the .First() function
DataContext db = new QuoteDataContext();
var quote = db.Quote.OrderBy(q => db.GetNewId()).First();
to be .Take(x)
DataContext db = new QuoteDataContext();
var quote = db.Quote.OrderBy(q => db.GetNewId()).Take(x);
replacing x with however many records you need.

Comment (0)



Comments are closed.