下午好,
我使用linqdatasource + entity framework iqueryable query填充了listview。
查询使用take(t-sql上的顶部),如下所示:
context.Categories().OrderBy(c=>c.Name).Take(20);
所以它给我带来了我想要的20条记录。
现在我想以随机顺序显示这20条记录。什么是最好的方法来实现这个?
答案 0 :(得分:3)
我相信这篇文章的答案就是你所需要的:
Linq to Entities, random order
编辑:
首先获得前20名的记录。然后使用您已经获取的前20个项目,将它们全部随机化为C#,根本不涉及数据库:
var yourRecords = context.Categories().OrderBy(c=>c.Name).Take(20); // I believe .Take() triggers the actual database call
yourRecords = yourRecords.OrderBy(a => Guid.NewGuid()); // then randomize the items now that they are in C# memory
答案 1 :(得分:1)
使用扩展方法非常简单,首先按名称排序,然后调用Take(在T-sql上排名)并随后随机化
context.Categories().OrderByName().Take(20).OrderByRandom();
public static IQueryable<Category> OrderByName(this IQueryable<Category> query)
{
return from c in query
orderby c.Name
select c;
}
public static IQueryable<T> OrderByRandom<T>(this IQueryable<T> query)
{
return (from q in query
orderby Guid.NewGuid()
select q);
}