在 LINQ Select 操作中有条件地包含 XElement?
Conditionally Include XElement in LINQ Select Operation?
我有工作代码,我在其中创建了一个 EnumerableRowCollection < XElement > 类型的新变量。我有一个新要求,其中必须根据文档类型值有条件地包含表示地址的 XElements 之一。
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。你能帮我实现这个吗?
更新(解决方案源自 tinstaafl 的回答):我使用了以下代码:
(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 24 }.Contains(DocumentType) ? xBillTo : null),
您可以使用三元运算符并将不需要 xBillTo 对象的条件响应设置为 null。
我有工作代码,我在其中创建了一个 EnumerableRowCollection < XElement > 类型的新变量。我有一个新要求,其中必须根据文档类型值有条件地包含表示地址的 XElements 之一。
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。你能帮我实现这个吗?
更新(解决方案源自 tinstaafl 的回答):我使用了以下代码:
(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 24 }.Contains(DocumentType) ? xBillTo : null),
您可以使用三元运算符并将不需要 xBillTo 对象的条件响应设置为 null。