This is actually my strategy to extract (for example) 5 random products from a list of products:
// extracts all products with Name Example
IList<Product> products = (from Product p in new Products()
where p.Name = "Example"
select p).ToList();
// I randomly order first 5 products
int upper = 1;
if (products.Count > 1)
{
Random r = new Random();
upper = Math.Min(5, products.Count);
for (int i = 0; i < upper; i++)
{
int randInd = r.Next(i, products.Count);
var temp = products[i];
products[i] = products[randInd];
products[randInd] = temp;
}
}
// I get the first 5
products = products.Take(upper);
I have to say : I'm annoyed about extract every time all records I need with LINQ, order them and get only few.
I think there is a waste of resources of this process, such as take ALL elements with LINQ if I need only 5.
Is there a method to extract with LINQ only records at some position in the table? I mean, if I have a table of 1000 rows, get only 5 rows randomly.
This will be the same, and the use of resources will improve.