Linq通过不排序来排序

本文关键字:排序 Linq | 更新日期: 2023-09-27 18:18:35

我有查询:

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);   

取正确的记录,但不排序。如果我将命令切换到asc/desc,它没有影响!谁能指出我怎么做才能先归还最新的记录?

编辑

如果Distinct()被删除,它将返回正确的结果顺序,但它现在一遍又一遍地返回相同的用户记录(我只希望每个用户出现一次)

Linq通过不排序来排序

听起来您希望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部分可能看起来令人困惑,但它很简单:按每个组中的第一个日期对组进行排序

Distinct正在撤消您的order。按照不同的顺序进行排序,就可以了。

修复它,这是工作查询:

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);  

您需要在select中指定一个日期,因此我取该特定用户的最后日期,并在Distinct()之后排序。很难解释,但如果你仔细阅读就会更有意义。

这个怎么样?

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);