使用“时间戳”列选择最近的条目

本文关键字:时间戳 最近 列选 使用 选择 | 更新日期: 2023-09-27 18:27:00

我有一个用于数据输入的简单网页(使用.NET 4.5和EF5构建)。每次用户更新条目时,都会创建一个新行,其TimeStamp值大于插入的前一行(SQL Server保证)。

在数据库中,原始数据如下所示。简而言之,数据意味着TransactionNumber=1被添加了一次,然后更新了两次。

+---------------+-------------------+-----------+--------------------+
| TransactionId | TransactionNumber |  Comment  |     TimeStamp      |
+---------------+-------------------+-----------+--------------------+
|             1 |                 1 | Bla       | 0x00000000000007D1 |
|             2 |                 1 | BlaBla    | 0x00000000000007D2 |
|             3 |                 1 | BlaBlaBla | 0x00000000000007D3 |
|             4 |                 2 | Hello     | 0x00000000000007D4 |
+---------------+-------------------+-----------+--------------------+

我想编写一个Linq查询,只获取每个TransactionNumber的最新值。考虑到上面的数据,我的查询将返回以下结果。

+---------------+-------------------+-----------+--------------------+
| TransactionId | TransactionNumber |  Comment  |     TimeStamp      |
+---------------+-------------------+-----------+--------------------+
|             3 |                 1 | BlaBlaBla | 0x00000000000007D3 |
|             4 |                 2 | Hello     | 0x00000000000007D4 |
+---------------+-------------------+-----------+--------------------+

到目前为止,我面临的最大问题是TimeStamp列的类型为byte[],我不知道如何进行字节比较。知道怎么做吗?

public class Transaction
{
    // ...
    [Timestamp]
    public Byte[] TimeStamp { get; set; }
}

使用“时间戳”列选择最近的条目

您可以使用下面的查询获得带有最新交易ID的交易编号。即使.NET备选方案是byte[],您仍然可以按时间戳列排序。

from transaction in db.Transactions
group transaction by transaction.TransactionNumber into g
select new
{
    TransactionNumber = g.Key,
    TransactionId = g.OrderByDescending(t => t.TimeStamp).Select(t => t.TransactionId).FirstOrDefault()
}

然后,您可以使用此查询的结果来选择剩余的列。