简体   繁体   中英

Linq to Xml - Create XAttribute conditionally

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!

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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