使用 DLR 简化 Linq to XML 查询
我有一个关于 Linq to XML 查询的问题,以及如何使用新的动态关键字使它们更具可读性。
目前我正在写这样的内容:
var result = from p in xdoc.Elements("product")
where p.Attribute("type").Value == "Services"
select new { ... }
我想写的是这样的内容:
var result = from p in xdoc.Products
where p.Type == "Services"
select new { ... }
我知道我可以使用 Linq to XSD 来做到这一点,这已经相当不错了,但显然这需要一个 XSD 模式,而我并不总是有一个。
我确信应该有一种方法可以使用 .NET 4.0 的新动态功能来实现这一目标,但我不确定如何或是否有人已经尝试过这一点。
显然,我会失去 Linq to XSD 的一些优点(类型化成员和编译时检查),但它不会比原始解决方案更糟糕,而且肯定会更具可读性。
有人有主意吗?
谢谢
I have a question regarding Linq to XML queries and how we could possibly make them more readable using the new dynamic keyword.
At the moment I am writing things like:
var result = from p in xdoc.Elements("product")
where p.Attribute("type").Value == "Services"
select new { ... }
What I would like to write is something like:
var result = from p in xdoc.Products
where p.Type == "Services"
select new { ... }
I know I can do this with Linq to XSD which is pretty good already, but obviously this requires an XSD schema and I don't always have one.
I am sure there should be a way to achieve this using the new dynamic features of .NET 4.0 but I'm not sure how or if anyone already had a go at this.
Obviously I would loose some of the advantages of Linq to XSD (typed members and compile time checks) but it wouldn't be worse than the original solution and would certainly be more readable.
Anyone has an idea?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此博客这篇文章探讨了在 LINQ to XML 场景中使用
ExpandoObject
的情况。This blog post explores a bit using
ExpandoObject
in LINQ to XML scenarios.