Getting random records from a table using LINQ to SQL

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

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

COMMENT

Leave a Comment

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

RELATED