Wednesday, 17 July 2013

Retrieve Random Record/Row from DataBase Table Using LINQ 2 SQL

var qry = from row in ctx.Customers
          where row.IsActive
          Order by row.Name 
          select row;
int count = qry.Count(); // 1st round-trip
int index = new Random().Next(count);

Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip

No comments:

Post a Comment