【问题标题】:Linq to Xml - Create XAttribute conditionallyLinq to Xml - 有条件地创建 XAttribute
【发布时间】:2012-01-18 21:55:49
【问题描述】:

我正在使用 Linq To Xml 从 DataSet 创建一个 Xml 文件。此数据集包含具有 1:M 关系的 Customer、Orders 表。

这是我的代码 sn-p -
如果任何当前客户订单的类型为“在线”,那么我正在尝试向 XElement 的“在线订单”添加几个属性。否则,如果没有“在线”类型的订单,那么我想创建一个空 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)),

以上代码运行良好。

但是如果我取消注释我添加一些额外属性的两行,我会得到几个编译错误,其中之一是 -

Invalid expression term ':'

请说明为什么会这样。

谢谢!

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

    您需要提供属性列表...

    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)),
    

    顺便说一句,如果代码不那么密集,您的代码会更容易跟踪/调试。为什么不把它分解成方法,或者使用局部变量呢?

    【讨论】:

    • 非常感谢!想知道为什么它没有进入我的脑海:-(。无论如何,'将其分解为方法'-我应该为 exp 创建方法。-返回 XAttribute 集合。抱歉,这是我第一次使用 Linq2Xml 进行实验,所以如果你可以指定我的代码中最引人注目的密集区域可以分解 - 请也为此提供指导。干杯!
    【解决方案2】:

    在这篇文章中查看我的 Set 函数:https://stackoverflow.com/a/8899367/353147

    然后做:

    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通常是一种扩展方法,所以如果你知道这些并转换它,它就会变成。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多