C# 如何将 LINQ 与动态集合一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18734996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use LINQ with dynamic collections
提问by
Is there a way to convert dynamic
object to IEnumerable
Type to filter collection with property.
有没有办法将dynamic
对象转换为IEnumerable
Type 以过滤具有属性的集合。
dynamic data = JsonConvert.DeserializeObject(response.Content);
I need to access something like this
我需要访问这样的东西
var a = data.Where(p => p.verified == true)
Any Ideas?
有任何想法吗?
采纳答案by Jon Skeet
So long as data
is an IEnumerable
of some kind, you can use:
只要data
是IEnumerable
某种类型,您就可以使用:
var a = ((IEnumerable) data).Cast<dynamic>()
.Where(p => p.verified);
The Cast<dynamic>()
is to end up with an IEnumerable<dynamic>
so that the type of the parameter to the lambda expression is also dynamic
.
的Cast<dynamic>()
是最终要与IEnumerable<dynamic>
使得参数lambda表达式的类型也是dynamic
。
回答by Yaser Moradi
Try casting to IEnumerable<dynamic>
尝试投射到 IEnumerable<dynamic>
((IEnumerable<dynamic>)data).Where(d => d.Id == 1);
This approach is 4x faster than other approachs.
这种方法比其他方法快 4 倍。
good luck
祝你好运
回答by user3407039
If you are able to, the ideal solution is to specify the type when deserializing, so to avoid having to cast later. This is a lot cleaner than the approaches suggested above.
如果可以,理想的解决方案是在反序列化时指定类型,以避免以后必须强制转换。这比上面建议的方法要干净得多。
So if you have -
所以如果你有 -
dynamic data = JsonConvert.DeserializeObject(response.Content);
Then simply change this to -
然后只需将其更改为 -
var data = JsonConvert.DeserializeObject<IEnumerable<dynamic>>(response.Content);