简体   繁体   English

Linq到Xml-有条件地创建XAttribute

[英]Linq to Xml - Create XAttribute conditionally

I am using Linq To Xml to create an Xml file from DataSet. 我正在使用Linq To Xml从DataSet创建Xml文件。 This dataset is having Customer, Orders table with 1:M relations. 该数据集包含具有1:M关系的Customer,Orders表。

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'. 如果任何当前客户订单的类型为“在线”,那么我试图向XElement“在线订单”添加多个属性。 Otherwise if there is no order with 'Online' type then I want to create an empty XElement like <OnlineOrder/> . 否则,如果没有'Online'类型的订单,那么我想创建一个空的XElement,例如<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! 谢谢!

You need to supply a list of attributes ... 您需要提供属性列表...

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 List<XAttribute>() { new XAttribute("Amount", o1.Amount),
                    new XAttribute("CardType", o1.CardType),
                    new XAttribute("Quantity", o1.Quantity) }
            ))
        : null)),

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? 为什么不将其分解为方法或使用局部变量?

See my Set function in this post: https://stackoverflow.com/a/8899367/353147 在这篇文章中查看我的Set函数: https : //stackoverflow.com/a/8899367/353147

Then do: 然后做:

XElement order = new XElement("OnlineOrder");
if( your condition )
{
    Set(order, "Amount", o1.Amount, true);
    Set(order, "CardType", o1.CardType, true);
    Set(order, "Quantity", o1.Quantity, true);
}

Set normally is an extension method, so if you know about those and convert it, it would become. 通常,Set是一种扩展方法,因此,如果您知道这些内容并将其转换,它将变为。

XElement order = new XElement("OnlineOrder");
if( your condition )
{
    order.Set("Amount", o1.Amount, true)
         .Set("CardType", o1.CardType, true)
         .Set("Quantity", o1.Quantity, true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM