[英]c# dynamic accessing child as IEnumerable
I have the following dynamic object as IEnumerable of type dynamic 我有以下动态对象作为dynamic类型的IEnumerable
[{
"id": 1,
"subList": [
{"specialId": 42},
{"specialId": 27}
]
},
{
"id": 2,
"subList": [
{"specialId": 13},
{"specialId": 14}
]
}]
I can get the objects into a IEnumerable of Dynamics and can run linq queries like the following 我可以将对象放入IEnumerable of Dynamics中,并可以运行linq查询,如下所示
listOfDynamics.Where(x => x.id == 2);
However what I would like to do is be able to do is match on the subList 但是我想做的是能够在subList上进行匹配
listOfDynamics.Where(x => ((IEnumerable)x.subList)).Where(y => y.specialId == 42));
so in the example above it would return the object with id of 1 but not the id of 2 因此在上面的示例中,它将返回ID为1而不是ID为2的对象
In your Where
you want to check if the subList
contains any element with specialId == 42
: 在你
Where
,你要检查,如果subList
包含任何元素specialId == 42
:
listOfDynamics.Where(x => ((IEnumerable<dynamic>)x.subList).Any(y => y.specialId == 42));
So Any()
is the method you want. 所以
Any()
是您想要的方法。
And you need to cast x.subList
to IEnumerable<dynamic>
instead of only IEnumerable
(as suggested by @Ivan-Stoev and @Derked in the comments). 并且您需要将
x.subList
为IEnumerable<dynamic>
而不是仅IEnumerable
(如@ Ivan-Stoev和@Derked在注释中所建议)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.