【问题标题】:Conditionally Include XElement in LINQ Select Operation?有条件地在 LINQ 选择操作中包含 XElement?
【发布时间】:2018-04-05 17:31:10
【问题描述】:

我有工作代码,我在其中创建了一个类型为 EnumerableRowCollection 的新 var。我有一个新要求,其中必须根据文档类型值有条件地包含表示地址的 XElement 之一。

public class Taxes
{
    public int DocumentType { get; set; }

    private XElement BuildBodyXML()
    {
        // other stuff

        Address billAddrObj = GetBillTo(dt);
        Address buyerAddrObj = GetBuyerPrimary(dt);

        var xBillTo = BuildAddress(billAddrObj, "BILL_TO");
        var xBuyer = BuildAddress(buyerAddrObj, "BUYER_PRIMARY");

        var INVOICE = from row in dt.AsEnumerable()
            select new XElement(tcr + "INVOICE", 
            xBillTo, // This one needs to be conditionally included based on DocumentType
            xBuyer, 
            // ... other elements ...
            new XElement(tcr + "INVOICE_NUMBER", row.Field<string>("DOCNUMBR").Trim()));

        // other stuff 

        return INVOICE;
    }

    public XElement BuildAddress(Address anAddress, string Name)
    {
        var xAddress = new XElement(tcr + Name);

        // other stuff 

        return xAddress;
    }
}

必须根据 DocumentType 的值有条件地包含 Bill To XElement。你能帮我实现这个吗?

更新(解决方案来自 t​​instaafl 的回答):我使用了以下代码:

(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 24 }.Contains(DocumentType) ? xBillTo : null),

【问题讨论】:

  • 你看过ternary operator吗?
  • 我考虑这个的方式是我在...选择 XElement、XElement、XElement 等...的上下文中。逗号的每个实例都应该表明一个 XElement 将被包括在内。我可以看到,如果我在两个两个逗号之间键入 null,我不会收到预编译错误。因此,使用三元运算符,我可以得到一个结果是 xBillTo 对象,而另一个结果是 null。这会在运行时正常运行吗?
  • 您能否将其设为具有空字段/属性的新 xBillTo 对象,而不是 null?话虽如此,我不明白为什么在三元组中使用 null 不起作用。
  • 使用三元运算符并为 false 条件提供 null 已经奏效。谢谢你挑战我尝试这个。我原以为它会失败,我需要一些“更漂亮”的东西。输入这个作为答案,我会标记它。

标签: c# linq xelement


【解决方案1】:

您可以使用三元运算符并将不需要 xBillTo 对象的条件响应设置为 null。

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 2016-11-02
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2023-04-10
    相关资源
    最近更新 更多