Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How might I take two random records from a list using Linq?

Tags:

c#

linq

How might I take two random records from a list using Linq?

like image 851
Ali Avatar asked Feb 21 '23 21:02

Ali


2 Answers

Random rnd = new Random();
var sequence = Enumerable.Range(1, 2).Select(n => lst[rnd.Next(0, lst.Count)]).ToList();
like image 191
ionden Avatar answered Feb 23 '23 09:02

ionden


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();
like image 35
AlfeG Avatar answered Feb 23 '23 09:02

AlfeG