我有查询:
var q =
(
from c in db.tblArcadeGamePlays
join a in db.tblProfiles on c.UserID equals a.UserID
where c.UserID != 0
orderby c.Date descending
select new { c.UserID, c.tblForumAuthor.Username, a.EmailAddress }
)
.Distinct()
.Take(12);
这会获取正确的记录,但不会对它们进行排序。如果我将orderby切换到asc / desc它没有任何影响!任何人都可以指出我能做些什么来最先返回记录吗?
修改
如果删除了Distinct()
,它会返回正确的结果排序,但它现在一遍又一遍地返回相同的用户记录(我只想让每个用户出现一次)
答案 0 :(得分:2)
区别在于撤消您的OrderBy。在分离之后进行排序,你会没事的。
答案 1 :(得分:2)
修正了它,这是工作查询:
var q = (from c in db.tblArcadeGamePlays
join a in db.tblProfiles on c.UserID equals a.UserID
where c.UserID != 0
select new {
c.UserID,
c.tblForumAuthor.Username,
a.EmailAddress,
Date = (from d in db.tblArcadeGamePlays where d.UserID == c.UserID orderby d.Date descending select new { d.Date}).Take(1).Single().Date
})
.Distinct()
.OrderByDescending(c=>c.Date)
.Take(12);
您需要在选择中指定日期,以便我为该特定用户选择最后一个日期,并在Distinct()
之后排序。如果你仔细阅读,很难解释,但更有意义。
答案 2 :(得分:2)
听起来你希望distinct
列表按每个集合中的最新项目排序,对吗?
为此,您应该使用group by
。您必须order
两次,每次一次,然后再次列出整个列表:
var q =
from s in
(
from c in db.tblArcadeGamePlays
join a in db.tblProfiles on c.UserID equals a.UserID
where c.UserID != 0
select new { c.UserId, c.TblForumAuthor.Username, a.EmailAddress, c.Date }
)
group s by new { g.UserId, g.Username, g.EmailAddress } into g
orderby g.OrderByDescending(s => s.Date).First().Date descending
select g.Key
)
.Take(12);
orderby
部分可能看起来令人困惑,但它只是:按照每个组中的第一个日期对组进行排序
答案 3 :(得分:-1)
这个怎么样?
var q = (from c in db.tblArcadeGamePlays
join a in db.tblProfiles on c.UserID equals a.UserID
where c.UserID != 0
select new { c.UserID, c.tblForumAuthor.Username, a.EmailAddress })
.OrderByDescending(c => c.Date)
.Distinct()
.Take(12);