LINQ:查询集合中的集合

发布于 2024-11-24 12:27:44 字数 444 浏览 1 评论 0原文

我有以下结构:

public class Customer
{
  public int ID { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int ID { get; set; }
  public int ProductID { get set; }
}

我需要获取订购 ProductID = 6 的客户的集合。流畅风格的 LINQ 会是什么样子?

我尝试了下面但没有运气:

var customers = allCustomers.SelectMany(c => c.Orders.Select(o => o.ProductID.Equals(6))).ToArray();

I have following structure:

public class Customer
{
  public int ID { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int ID { get; set; }
  public int ProductID { get set; }
}

I need to get the collection of customers that ordered ProductID = 6. What would the fluent style LINQ look like?

I tried below with no luck:

var customers = allCustomers.SelectMany(c => c.Orders.Select(o => o.ProductID.Equals(6))).ToArray();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

灯角 2024-12-01 12:27:44

varcustomers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));

var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));

笑咖 2024-12-01 12:27:44
allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6))
allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6))
老街孤人 2024-12-01 12:27:44
var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
var customers = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
萌能量女王 2024-12-01 12:27:44

看起来你想要:

var query = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));

Looks like you want:

var query = allCustomers.Where(c => c.Orders.Any(o => o.ProductID == 6));
故乡的云 2024-12-01 12:27:44

一个很好的方法是从另一边尝试像这样

var customers from p in Order where p.ProductId == 6 select p.Customer

当然你需要在 Order 类中添加 Customer 属性,如下所示

public class Order
{
  public int ID { get; set; }
  public int ProductID { get set; }
  public Customer Customer { get; set; }
}

A nice way would be to try from the other side like this

var customers from p in Order where p.ProductId == 6 select p.Customer

And of course you need the add the Customer property in the Order class like this

public class Order
{
  public int ID { get; set; }
  public int ProductID { get set; }
  public Customer Customer { get; set; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文