【问题标题】:Is it possible to do a Group By in LINQ but then only return the 'most recent' item (per group)?是否可以在 LINQ 中进行分组,但只返回“最新”项目(每组)?
【发布时间】:2013-07-15 08:49:05
【问题描述】:

我正在尝试在 .NET LINQ 中按组返回最近的项目。

这让我想起了在 Sql 中执行PARTITION,我们在其中分区并获得每个分区的前 1 个,按最近的(每个分区)排序。

到目前为止,我已经开始使用 linq 代码了..

from p in products
group p by new {p.Provider.ProductId, p.Provider.Name} into g

但我不知道如何添加order by p.CreatedOn desc 并获得.Take(1)每个分区/组

【问题讨论】:

  • select g.OrderByDescending(x => x.CreatedOn).First() ?
  • 或 FirstOrDefault() 会更好?
  • 不! omg ... /me跑去试试...
  • @Alicia 如果没有任何项目,首先就不会有一个组,所以OrDefault 将是多余的

标签: c# .net linq linq-to-objects


【解决方案1】:

类似(附加在查询末尾):

select new {
    g.Key,
    Product = g.OrderByDescending(x => x.CreatedOn).First()
}

应该做这项工作;或者更方便:

select new {
    g.Key.ProductId,
    g.Key.Name,
    Product = g.OrderByDescending(x => x.CreatedOn).First()
}

或者,如果您不需要明确需要密钥(因为它无论如何都在项目下可用),那么只需:

select g.OrderByDescending(x => x.CreatedOn).First()

基本上,每个g 都是一个IGrouping<T>(对于某些匿名T),这意味着每个g 一个.Key 属性是您的组,并且每个@ 987654329@ 一个IEnumerable<>的原始元素序列(大概是Product)。

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多