• simon@simonholman.blog

Getting random records from a table using LINQ to SQL

Share this post

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

I needed to get a number of random records from a table. 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.

Share this post

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Leave a Reply