【发布时间】:2011-12-07 14:37:03
【问题描述】:
这实际上是我从产品列表中提取(例如)5 个随机产品的策略:
// 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);
我不得不说:每次使用 LINQ 提取我需要的所有记录、订购它们并且只得到很少的记录时,我都感到很恼火。
我认为这个过程会浪费资源,例如如果我只需要 5 个,就使用 LINQ 获取所有元素。
有没有一种方法可以仅使用 LINQ 提取表中某个位置的记录?我的意思是,如果我有一个 1000 行的表,那么随机只获取 5 行。
这将是相同的,并且资源的使用将得到改善。
【问题讨论】:
-
是的,方法很少!但我没有要求任何人:(