简体   繁体   English

使用LINQ选择最新的独特商品

[英]Select latest, distinct item with LINQ

I have a list of objects that each look something like this: 我有一个对象列表,每个对象看起来像这样:

public class Item
{
    public string Id { get; set; }
    public DateTime Timestamp { get; set; }
    public string Status { get; set; }
}

In my list, the same Id may appear repeatedly, but with different Timestamp and Status values. 在我的列表中,相同的ID可能会重复出现,但是时间戳和状态值不同。 So an example list (in JSON notation) might look like this: 因此,示例列表(采用JSON表示法)可能如下所示:

[
  {
    "Id": "123",
    "Timestamp": "2017-06-21T08:00:00.000Z",
    "Status": "Ordered"
  },
  {
    "Id": "789",
    "Timestamp": "2017-06-20T09:00:00.000Z",
    "Status": "Ordered"
  },
  {
    "Id": "123",
    "Timestamp": "2017-06-20T10:00:00.000Z",
    "Status": "Dispatched"
  },
]

Note that item "123" appears twice - ordered at 8am, dispatched at 10am. 请注意,项目“ 123”出现两次-上午8点订购,上午10点发货。

Is there a way to use LINQ to remove the duplicates (by Id) from that list, so we're left with just the latest item (by Timestamp) for each Id? 有没有一种方法可以使用LINQ从该列表中删除重复项(按ID),所以我们只剩下每个ID的最新项(按时间戳记)? In other words, I just want a list containing the latest status for each item: 换句话说,我只想要一个包含每个项目的最新状态的列表:

[
  {
    "Id": "789",
    "Timestamp": "2017-06-20T09:00:00.000Z",
    "Status": "Ordered"
  },
  {
    "Id": "123",
    "Timestamp": "2017-06-20T10:00:00.000Z",
    "Status": "Dispatched"
  },
]

Try GroupBy by Id and sort each group by TimeStamp : 尝试按Id进行GroupBy并按TimeStamp对每个组进行排序:

IEnumerable<Item> source = ...

var result = source
  .GroupBy(item => item.Id)
  .Select(chunk => chunk
     .OrderByDescending(item => item.TimeStamp)
     .First())
  .ToArray(); // if you want materialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM