I'm trying to come up a LINQ SELECT statement in C# to select random items from specific object instead of ordered items. how do i translate below syntax to random select
random = _dbase.OrderBy(x => x.company).Take(1000);
CodePudding user response:
You cannot select a random item from an IEnumerable
because it's a generator that yields values. It has no size so you might be dealing with an infinite IEnumerable
which makes the selection of a random item impossible.
A work around would be to create a List<T>
(which has a size) from your initial collection and then select a random item.
IEnumerable<object> myCollection = ...;
var myList = myCollection.ToList();
var rng = new Random();
var randomIndex = rng.Next(0, myList.Count);
var randomItem = myList[randomIndex];
But in your case, you would prefer not to fetch all data of your table. Instead you could make the calculation inside the sql request.
Here's a link showing how to do it.
Sneak peek in case it becomes invalid
// DO NOT USE THIS FOR MORE THEN 100 ROWS
var randomRecord = foos.OrderBy( x=> SqlFunctions.Rand() ).FirstOrDefault();
// USE THIS FOR MORE THEN 100 ROWS
var random = Math.Random(foos.Count());
var randomRecord = foos.OrderBy( x=> x.id ).Skip( random ).FirstOrDefault();