简体   繁体   English

使用Linq查询多层嵌套数组

[英]Query With Multi-Level Nested Arrays Using Linq

I have a model such as: 我有一个模型,例如:

{
  nestedArray1: [
    {
      nestedArray2: [
        {
          id: 1
        }
      ]
    }
  ]
}

I am trying to get the items which contain nestedArray2 with the id value that is among the list x = [1, 2, 3, 4, 5, ...] . 我正在尝试获取包含nestedArray2的ID为列表x = [1, 2, 3, 4, 5, ...]

I tried to run the following query with no avail: 我尝试运行以下查询无济于事:

var query = model.AsQueryable().Where(m => m.nestedArray1.Any(s => s.nestedArray2.Any(m => ids.Any(id => id == m.id))));
var results = query.ToListAsync();

It says that any filter is unsupported. 它说不支持任何过滤器。

What is the proper way of writing such a query using Linq? 使用Linq编写这样的查询的正确方法是什么?

NOTE: 注意:

Here is how I can do it using Mongo query syntax: 这是使用Mongo查询语法的方法:

db.getCollection('model').find({
    "nestedArray1": {
        $elemMatch:{
            nestedArray2:{
                $elemMatch:{
                  "id" : {$in: [1, 2, 3, 4, 5] }
            }
        }
    }
}

}) })

And here is how I can do it using C# without Linq query syntax: 这是我如何在不使用Linq查询语法的情况下使用C#做到这一点:

var ids = new List<int>() { 1, 2, 3, 4, 5};
var filter = new FilterDefinitionBuilder<Model>()
        .ElemMatch(p => p.nestedArray1, new FilterDefinitionBuilder<NestedModel1>()
            .ElemMatch(s => s.nestedArray2, new FilterDefinitionBuilder<NestedModel2>()
                .In(m=> m.id, ids)));
return await Collection.Find(filter).ToListAsync();

According to your model the items of nestedArray2 only have a field with one ID. 根据您的模型,nestedArray2的项只有一个具有一个ID的字段。

So considering your example above, you should have something like this (i think): 因此,考虑到上面的示例,您应该有以下内容(我认为):

var query = model.AsQueryable().Where(m => m.nestedArray1.Any(s => s.nestedArray2.Any(m => ids.Contains(m.id))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM