我正在尝试从一个具有不同类别的DB表中获取记录。我想从每个级别获取一个随机记录。
我尝试使用以下方法来实现这一点:
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条。
我做错了什么?
发布于 2017-01-13 01:42:52
这是因为每个Take都应用于链中所有在前Union的结果,即
a.Take(1).Union(b).Take(1)您需要将括号添加到Take%s中,以确保
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();发布于 2017-01-13 01:45:57
如果我没理解错你的要求,你就不能做这样的事吗?
Random rnd = new Random();
var results = db.tblName.GroupBy( q => q.category )
.Select( g => g.ElementAt(rnd.Next(0, g.Count())) ).ToList();https://stackoverflow.com/questions/41619619
复制相似问题