How might I take two random records from a list using Linq?
-
check this post... [1]: http://stackoverflow.com/questions/1364033/linq-take-question – BizApps Apr 09 '12 at 03:46
5 Answers
Random rnd = new Random();
var sequence = Enumerable.Range(1, 2).Select(n => lst[rnd.Next(0, lst.Count)]).ToList();

- 12,536
- 1
- 45
- 37
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();

- 1,475
- 4
- 18
- 33
-
http://blogs.msdn.com/b/ericlippert/archive/2011/01/31/spot-the-defect-bad-comparisons-part-four.aspx – L.B Apr 09 '12 at 06:30
-
-
1Depending on the sort algorithm used, that may result in an infinite loop.( A>B at time t1 and A – L.B Apr 09 '12 at 09:32
There is no direct way. You can try this, not pretty though.
int randomRecord = new Random().Next() % List.Count(); //To make sure its valid index in list
var qData = List.Skip(randomRecord).Take(1);
var qValue = qData.ToList().First();

- 21,087
- 11
- 87
- 112
-
-
1
-
I think, % will always give max remainder of List.Count() - 1, which would be the last element. – A G Apr 09 '12 at 03:49
-
You're taking only one and you should take two, and this increase the odds of the last item in the list. **Your answer isn't random enough.** – gdoron Apr 09 '12 at 03:49
-
I think the above logic can be enhanced to take 2 random elements easily using the ? operator. Again I am not saying I have the perfect answer. – A G Apr 09 '12 at 03:53
This is what ended up working for me, it ensures no duplicates are returned:
public List<T> GetRandomItems(List<T> items, int count = 3)
{
var length = items.Count();
var list = new List<T>();
var rnd = new Random();
var seed = 0;
while (list.Count() < count)
{
seed = rnd.Next(0, length);
if(!list.Contains(items[seed]))
list.Add(items[seed]);
}
return list;
}

- 2,650
- 3
- 18
- 34
Why do you want to use Linq to get two random records?
Create a Random instance and get two random number whose values are less than the length of the list.
List has Indexer property, so doing List[index] is not costly.
Keep it simple. Always prefer readability. If you just make things complicated, the programmers who are going to maintain your code will have hard time.
I am just curious to know why exactly you want to do this in Linq? That just seems like a overhead to me.
am I missing something?

- 7,156
- 12
- 45
- 57
-
because i want display 2 records on my page which will change after every postback. so i need 2 get 2 random records from list – Ali Apr 09 '12 at 04:05