0

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!

inutan
  • 10,558
  • 27
  • 84
  • 126

2 Answers2

3

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?

ColinE
  • 68,894
  • 15
  • 164
  • 232
  • Thank you so much! Wonder why it didn't come into my head :-(. Anyways, 'break it up into methods' - should I create methods for exp. - to return XAttribute collection. Sorry this is my first experiment with Linq2Xml so if you can specify the most eye-catching dense area in my code that can be broken up - please guide for that too. Cheers! – inutan Jan 18 '12 at 22:09
0

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);
}
Community
  • 1
  • 1
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69