我正在尝试从具有不同类别的数据库表中获取记录。我想从每个级别获取1个随机记录。
我尝试使用以下方法实现此目的:
var results = (from o in db.tblName
where o.category== 1
orderby Guid.NewGuid()
select o).Take(1).Union
(from o in db.tblName
where o.category == 2
orderby Guid.NewGuid()
select o).Take(1).Union
(from o in db.tblName
where o.category == 3
orderby Guid.NewGuid()
select o).Take(1).Union
(from o in db.tblName
where o.category == 4
orderby Guid.NewGuid()
select o).Take(1);
使用上面的代码导致获取1条记录而不是4条。
我做错了什么?
答案 0 :(得分:0)
这是因为每个Take
都应用于链中所有前面的Union
s的结果,即
a.Take(1).Union(b).Take(1)
您需要在Take
中添加括号以确保它是
a.Take(1).Union(b.Take(1))
您的查询应如下所示:
var results =
((from o in db.tblName where o.category== 1 orderby Guid.NewGuid() select o).Take(1))
.Union((from o in db.tblName where o.category == 2 orderby Guid.NewGuid() select o).Take(1))
.Union((from o in db.tblName where o.category == 3 orderby Guid.NewGuid() select o).Take(1))
.Union((from o in db.tblName where o.category == 4 orderby Guid.NewGuid() select o).Take(1));
您可以按如下方式进一步简化查询:
var categories = new[] {1, 2, 3, 4};
var result = categories.Select(
c => (from o in db.tblName where o.category==c orderby Guid.NewGuid() select o).Take(1)
).Distinct();
答案 1 :(得分:0)
你不能做这样的事。
Random rnd = new Random();
var results = db.tblName.GroupBy( q => q.category )
.Select( g => g.ElementAt(rnd.Next(0, g.Count())) ).ToList();