【问题标题】:What's the best way to construct this LINQ query using orderby and group by?使用 orderby 和 group by 构造此 LINQ 查询的最佳方法是什么?
【发布时间】:2011-06-04 11:45:03
【问题描述】:

我正在学习 LINQ,它让我了解了如何弄清楚如何从 mongoDB 以我想要的方式获取数据。似乎应该有比这更好的方法。

基本前提是在UserMessage 集合中存在一个我正在尝试分组的ID。我想通过UserMessage 中的DateCreated 订购。

也可以为组返回一个 COUNT,但我想我已经准备好寻求帮助了。 :)

//get from the db all the mssages to this user and from
var result = (from messages in session.All<UserMessage>()
              where messages.To == User.Identity.Name ||
                 messages.From == User.Identity.Name
              orderby messages.DateCreated descending
              select messages).ToList().GroupBy(t => t.AssociatedMessageID);
              //.Select(g => new { AssociatedMessageID = g.Key });

var result2 = from m in result.ToList()
              orderby m.First().DateCreated descending
              select m;

List<IGrouping<string,UserMessage>> aryMsg = result2.ToList();

foreach (IGrouping<string,UserMessage> um in aryMsg)
{
    //in this loop assign various members of each UserMessage to a view model
}

【问题讨论】:

    标签: linq count group-by sql-order-by


    【解决方案1】:

    没有必要进行那么多ToList() 转换(除非 mongoDB 不支持分组)。它只会损害性能。组的第二次排序不是必需的,因为所有消息都已排序,因此组也应排序。最终,我认为您的查询是这样的:

    var aryMsg = (from um in session.All<UserMessage>()
                  where um.To == User.Identity.Name
                     || um.From == User.Identity.Name
                  orderby um.DateCreated descending)
                 .AsEnumerable()
                 .GroupBy(um => um.AssociatedMessageID)
                 .ToList();
    

    【讨论】:

    • mongoDB 驱动程序抛出异常 - 不支持“GroupBy”方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多