LINQ - 如何按日期排序

时间:2014-05-23 09:14:36

标签: c# linq

我有下表(记录):

RecordID int,
Nickname nvarchar(max),
DateAdded datetime

我需要按昵称记录的最大数量分组。我做到了:

        var users = (from i in db.Records
                     where i.Form.CompetitionID == cID
                     group i by i.Nickname into g
                     orderby g.Count() descending
                     select new TopUserModel()
                     {
                         Nickname = g.Key,
                         Position = g.Count()
                     }).Take(100).ToList();

它有效

现在我需要按日期对其进行排序(谁先获得最大记录)。 我应该有这样的要求:

select Nickname, Count(*) as Result, MAX(DateAdded) as MDate from Records group by Nickname order by Result Desc, MDate Asc

LINQ如何做到这一点?

5 个答案:

答案 0 :(得分:3)

我认为这就是你想要的。我使用了Linq的扩展版本,这可能更容易。我们的想法是在GroupBy之后计算MaxCount和MaxDate,以便您可以在下一个OrderBy子句中使用它。

db.Records
.Where(i => i.Form.CompetitionID == cID)
.GroupBy(i => i.Nickname)
.Select(g => new { MaxCount = g.Count(), MaxDate = g.Max(i => i.DateAdded), Nickname = g.Key})
.OrderByDescending(gx => gx.MaxCount)
.ThenByDescending(gx => gx.MaxDate)
.Select(gx => new TopUserModel()
{
     Nickname = gx.Nickname,
     Position = gx.MaxCount
}).Take(100).ToList();

答案 1 :(得分:1)

我认为你要求的是:

...
select new TopUserModel()
{
    Nickname = g.Key,
    Position = g.Count()
    Date = g.Max(r => r.DateAdded)
}).Take(100).OrderByDescending(t => t.Position).ThenBy(t => t.Date).ToList();

当您使用group时,密钥就是您的分组,但可枚举是您已分组的所有记录,因此您仍然可以在其上使用汇总功能。

如果要按多列排序,可以使用上面的链接将它们按顺序排列。

答案 2 :(得分:0)

    var users = (from i in db.Records
                         where i.Form.CompetitionID == cID
                         group i by new {i.Nickname} into g
                         orderby g.Count() descending, 
                         select new TopUserModel()
    {
        Nickname = g.Key,
        Position = g.Count()
        Date = g.Max(r => r.DateAdded)
    }).Take(100

).OrderBy(c => c.Date).ToList();

答案 3 :(得分:0)

只需将昵称的最大日期添加到订购中。您还可以为位置引入新的范围变量:

var users = (from r in db.Records
             where r.Form.CompetitionID == cID
             group r by r.Nickname into g
             let position = g.Count()
             orderby position descending, g.Max(r => r.DateAdded)
             select new TopUserModel {
                 Nickname = g.Key,
                 Position = position
             }).Take(100).ToList();

答案 4 :(得分:-1)

问题已经在这里得到解答:OrderBy a date field with linq and return ToList()

在用户对帐单的末尾添加

    .OrderBy(e => e.Date).ToList();