Linq to Xml - 有条件地创建 XAttribute
我正在使用 Linq To Xml 从 DataSet 创建 Xml 文件。该数据集包含具有 1:M 关系的 Customer、Orders 表。
这是我的代码片段 -
如果任何当前客户订单的类型为“Online”,那么我尝试向 XElement“OnlineOrder”添加多个属性。否则,如果没有“Online”类型的订单,那么我想创建一个空的 XElement,如
。
new XElement("OnlineOrder", ((customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(o=>o.Type=="Online").Any())
? customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(p1 => p1.Type == "Online").Select(
(o1 => new XAttribute("Amount", o1.Amount)//,
//new XAttribute("CardType", o1.CardType),
//new XAttribute("Quantity", o1.Quantity)
))
: null)),
上面的代码工作正常。
但是,如果我取消注释添加一些额外属性的两行,我会收到几个编译错误,其中之一是 -
Invalid expression term ':'
请指导为什么会发生这种情况。
谢谢你!
I am using Linq To Xml to create an Xml file from DataSet. This dataset is having Customer, Orders table with 1:M relations.
Here is my code snippet -
If any of the current customer order is of type 'Online' then I am trying to add several attributes to XElement 'OnlineOrder'. Otherwise if there is no order with 'Online' type then I want to create an empty XElement like <OnlineOrder/>
.
new XElement("OnlineOrder", ((customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(o=>o.Type=="Online").Any())
? customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(p1 => p1.Type == "Online").Select(
(o1 => new XAttribute("Amount", o1.Amount)//,
//new XAttribute("CardType", o1.CardType),
//new XAttribute("Quantity", o1.Quantity)
))
: null)),
Above code is working fine.
But if I uncomment two lines where I am adding some extra attribute, I get several compile error with one of them being -
Invalid expression term ':'
Please guide why this is happening.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要提供属性列表...
顺便说一句,如果代码不是那么密集,那么您的代码将更容易遵循/调试。为什么不将其分解为方法或使用局部变量?
You need to supply a list of attributes ...
By the way, your code would be much easier to follow / debug if it were not so dense. Why not break it up into methods, or use local variables?
请参阅这篇文章中的我的 Set 函数: https://stackoverflow.com/a/8899367/353147
然后执行:
正常设置是一个扩展方法,所以如果你了解这些并转换它,它就会变成。
See my Set function in this post: https://stackoverflow.com/a/8899367/353147
Then do:
Set normally is an extension method, so if you know about those and convert it, it would become.