0

I have working code in which I create a new var of type EnumerableRowCollection < XElement >. I have a new requirement where one of the XElements representing an Address must be conditionally included based on a Document Type value.

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;
    }
}

The Bill To XElement must be included conditionally based on the value of DocumentType. Can you help me achieve this?

UPDATE (Solution derived from answer by tinstaafl): I used the following code:

(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 24 }.Contains(DocumentType) ? xBillTo : null),
CodenameCain
  • 573
  • 1
  • 9
  • 22
  • Have you looked at the [ternary operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator)? – tinstaafl Apr 05 '18 at 17:43
  • The way I think about this is I'm in the context of ...select XElement, XElement, XElement, etc.... Each instance of a comma should indicate that an XElement is going to be included. I can see that if I type null between two two commas I am not getting a pre-compilation error. So with the ternary operator I could have one result be the xBillTo object and the other be null. Is that going to behave properly at runtime? – CodenameCain Apr 05 '18 at 17:57
  • Instead of null could you make it a new xBillTo object with empty fields/properties? That being said, I don't see why using null in a ternary shouldn't work. – tinstaafl Apr 05 '18 at 18:19
  • Using the ternary operator and providing null for the false condition has worked. Thank you for challenging me to try this. I had thought it would fail and I would need something "fancier". Enter this as an answer and I will mark it. – CodenameCain Apr 05 '18 at 19:29

1 Answers1

0

You could use the ternary operator and set the conditional response that doesn't require the xBillTo object to null.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22