首页 > 解决方案 > LINQ 选择列表中的所有孤儿

问题描述

我正在使用 C# 中的以下模型

public class Bill
{
    public Guid Id { get; set; }

    public Document Document { get; set; }
}

public class Document
{
    public Guid Id { get; set; }

    public List<Payment> Payments { get; set; }
}

public class Payment
{
    public Guid Id { get; set; }
}

我想Payments使用 LINQ 选择所有没有父母的人。

我从几个 SO 答案中了解到以下技术,如下所示

List<Payment> paymentList = db.Payments
    .Where(p => !db.Documents.Any(d => d.Payment.Id == p.Id))

但如果Document只包含一个Payment,而不是整个列表,则此方法有效。

您知道如何调整查询以检索所有孤立的付款吗?

标签: c#linqentity-framework-core

解决方案


 // All the payments whose id is not contained in any of all the           
//Documents.Payments
   List<Payment> paymentList = db.Payments
        .Where(p => db.Documents.SelectMany(d => d.Payments)
        .All(p2 => p2.Id != p.Id));

推荐阅读