我有以下动态对象作为动态类型的 IEnumerable
[{
"id": 1,
"subList": [
{"specialId": 42},
{"specialId": 27}
]
},
{
"id": 2,
"subList": [
{"specialId": 13},
{"specialId": 14}
]
}]
我可以将对象放入 Dynamics 的 IEnumerable 中,并可以像下面这样运行 linq 查询
listOfDynamics.Where(x => x.id == 2);
但是我想做的是匹配子列表
listOfDynamics.Where(x => ((IEnumerable)x.subList)).Where(y => y.specialId == 42));
所以在上面的例子中,它会返回 id 为 1 而不是 id 为 2 的对象
最佳答案
在你的Where
你想检查 subList
包含带有 specialId == 42
的任何元素:
listOfDynamics.Where(x => ((IEnumerable<dynamic>)x.subList).Any(y => y.specialId == 42));
所以 Any()
是您想要的方法。
你需要投 x.subList
至 IEnumerable<dynamic>
而不仅仅是 IEnumerable
(正如@Ivan-Stoev 和@Derked 在评论中所建议的那样)。
关于c# 动态访问 child 作为 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37291808/