c# - 带有子查询的 Linq 查询

标签 c# linq

我有一个名为 UserPaymentHistory 的实体,其中包含 Id、UserId、Price、PaymentDate。 我需要获取具有最后一个付款日期的用户的那一行。

我可以这样查询:

var lastPaymentDate =
    db.Repository<UserPayment>()
            .Where(u => u.UserId == 1)
            .Select(x => x.PaymentDate)
            .Max();

然后:

var userPayment = db.Repository<UserPayment>()
                      .Where(u => u.UserId == request.UserId 
                      && u.PaymentDate == lastPaymentDate).Single();

有什么方法可以在一次查询中获取该记录? :)

最佳答案

按 PaymentDate 降序排列付款并选择第一个:

var userPayment = db.Repository<UserPayment>()
                      .Where(u => u.UserId == request.UserId)
                      .OrderByDescending(u => u.PaymentDate)
                      .FirstOrDefault();

关于c# - 带有子查询的 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19013845/

相关文章:

c# - CSV 到对象模型映射

c# - 短路 linq 查询抛出 null 错误

c# - Entity Framework 连接向导找不到我的数据库

c# - 升级到 ASP.NET Core 2.0 后无法创建迁移

c# - 我在反序列化过程中遇到下一个异常 : "Invalid field in source data: 0". 如何找出源代码中的原因/错误位置?

c# - EventHubClient.SendBatchAsync - 它是线程安全的吗?

Linq 2 Sybase ASE 数据库?有什么选择?

c# - 如何使此 LINQ 查询更快?

c# - 不能将文本数据类型选为 DISTINCT,因为它不可比较

c# - OledbConnection.Dispose() 是否关闭连接?