How might I take two random records from a list using Linq?
Random rnd = new Random();
var sequence = Enumerable.Range(1, 2).Select(n => lst[rnd.Next(0, lst.Count)]).ToList();
For Linq-to-Objects
and EF4
it's pretty simple
db.Users.OrderBy(r => Guid.NewGuid()).Take(2)
For Linq-to-SQL
You can check this article
http://michaelmerrell.com/2010/03/randomize-result-orders-in-t-sql-and-linq-to-sql/
Add function Random mapped to SQL function NEWID
to DataContext.
partial class DataContext
{
[Function(Name = "NEWID", IsComposable = true)]
public Guid Random()
{
throw new NotImplementedException();
}
}
Usage
var qry = from row in DataBase.Customers
where row.IsActive
select row;
int count = qry.Count();
int index = new Random().Next(count);
Customer cust = qry.Skip(index).FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With