You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将IEnumerable<XElement>转换为嵌套对象List<DistributorCustomer>

解决嵌套XML转实体类List的LINQ to XML实现

没问题,用LINQ to XML处理嵌套对象其实很直接,我们可以在Select方法里直接嵌套构造对应的实体类对象,完全不需要显式循环。这里是针对你的场景的完整实现:

// 基于你已获取的customers集合进行转换
var distributorCustomers = customers.Select(customer => new DistributorCustomer
{
    CustomerName = (string)customer.Element("CustomerName"),
    AccountNumber = (string)customer.Element("AccountNumber"),
    // 构造嵌套的BillingAddress对象
    BillingAddress = customer.Element("BillingAddress") is XElement billingAddr
        ? new BillingAddress
        {
            Address1 = (string)billingAddr.Element("Address1"),
            Address2 = (string)billingAddr.Element("Address2"),
            City = (string)billingAddr.Element("City"),
            State = (string)billingAddr.Element("State"),
            Zip = (string)billingAddr.Element("Zip"),
            Country = (string)billingAddr.Element("Country")
        }
        : null,
    // 构造嵌套的ShippingAddress对象
    ShippingAddress = customer.Element("ShippingAddress") is XElement shippingAddr
        ? new ShippingAddress
        {
            Address1 = (string)shippingAddr.Element("Address1"),
            Address2 = (string)shippingAddr.Element("Address2"),
            City = (string)shippingAddr.Element("City"),
            State = (string)shippingAddr.Element("State"),
            Zip = (string)shippingAddr.Element("Zip"),
            Country = (string)shippingAddr.Element("Country")
        }
        : null
}).ToList();

关键细节说明:

  • 安全获取元素值:使用(string)XElement的方式而非XElement.Value,这样当元素不存在或者为空时,会返回null或者空字符串,避免抛出NullReferenceException,让代码更健壮。
  • 空值检查:用C#的模式匹配(customer.Element("BillingAddress") is XElement billingAddr)先判断嵌套的地址元素是否存在,再构造对应的实体对象。如果你的业务场景中每个Customer必然包含这两个地址,也可以省略这个检查,直接构造对象。
  • 最终转换为List:调用ToList()方法将IEnumerable<DistributorCustomer>转换为你需要的List<DistributorCustomer>类型。

这样就完成了从嵌套XML到实体类列表的转换,全程用LINQ实现,没有显式循环。

内容的提问来源于stack exchange,提问作者Casey Crookston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:28:08