在LINQ查询中替换ElementAt以覆盖多个元素

icomxhvb  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(150)

I want to retrieve a list of Orders based on a multiple Location lists.
For context: a Group can have a multiple Location s (one-to-many) and an Order has one Location (many-to-one). I want to get all the Orders of a Group based on the Location s it has.
The following works for the first element in the list of Group s:

List<Order> orders = _context.Orders
    .Where(o => groups.ElementAt(0).Locations.Contains(o.Location))
    .ToList()

I want to change it such that it will not only check the first Group element, but all of them. Help is appreciated.

9rnv2umw

9rnv2umw1#

由于groups只是一个变量,因此您可以在运行查询之前使用SelectMany来展平嵌套层次结构:

var locations = groups.SelectMany(x => x.Locations).ToArray();

这基本上改变了嵌套层次结构

G1
  L11
  L12
G2
  L21
  L22

一个简单的位置列表:

L11
L12
L21
L22

之后,您可以在查询中使用这些位置:

List<Order> orders = _context.Orders
  .Where(o => locations.Contains(o.Location))
  .ToList()

如果组可以包含重复的位置,则还可以在SelectMany之后添加Distinct

m528fe3b

m528fe3b2#

这是你要找的吗?

var result = orders
    .Where(o => groups.All(f => 
        f.Locations.Contains(o.Location))).ToList();

相关问题