使用LINQ从含嵌套数组的C#类中提取父子属性值的方案咨询
结论
你的需求完全可以通过LINQ实现,并且LINQ是该场景的最佳实践之一。
这种多层嵌套集合的扁平化映射、按子属性过滤提取父级属性是LINQ的典型适用场景,相比手写多层foreach循环,LINQ写法可读性更高、维护成本更低,且性能开销在绝大多数业务场景下可以忽略。
实现代码
1. 全量数据转换(生成你要求的完整ModelList列表)
如果你需要把所有嵌套层级的customerModel对应的父级属性都提取出来,直接用以下查询语法即可,代码中已添加空值防护,避免某层级数组为null时抛出空引用异常:
// 假设catalog是你已经反序列化得到的Productcatalog类实例 var modelList = ( from family in catalog.result.productFamily ?? Enumerable.Empty<Productfamily>() from category in family.productCategory ?? Enumerable.Empty<Productcategory>() from construction in category.productConstruction ?? Enumerable.Empty<Productconstruction>() from line in construction.productLine ?? Enumerable.Empty<Productline>() from productModel in line.productModel ?? Enumerable.Empty<Productmodel>() from customerModel in productModel.customerModel ?? Enumerable.Empty<Customermodel>() select new ModelList { productConstructionId = construction.id, productConstructionName = construction.name, productLineId = line.id, productLineName = line.name, customerModelId = customerModel.id, customerModelName = customerModel.name } ).ToList();
2. 按最深层属性过滤提取(仅返回符合条件的记录)
如果你仅知道最深层customerModel的取值(比如id为cModelId2),只需要在查询中加where条件即可,上层父级属性可以直接从对应层级的上下文变量中提取:
string targetCustomerModelId = "cModelId2"; var filteredModelList = ( from family in catalog.result.productFamily ?? Enumerable.Empty<Productfamily>() from category in family.productCategory ?? Enumerable.Empty<Productcategory>() from construction in category.productConstruction ?? Enumerable.Empty<Productconstruction>() from line in construction.productLine ?? Enumerable.Empty<Productline>() from productModel in line.productModel ?? Enumerable.Empty<Productmodel>() from customerModel in productModel.customerModel ?? Enumerable.Empty<Customermodel>() where customerModel.id == targetCustomerModelId // 仅过滤符合条件的最深层记录 select new ModelList { productConstructionId = construction.id, productConstructionName = construction.name, productLineId = line.id, productLineName = line.name, customerModelId = customerModel.id, customerModelName = customerModel.name } ).ToList();
补充说明
- 如果你的数据体量极大,可以直接返回
IEnumerable<ModelList>类型使用延迟加载,不需要一次性调用ToList()加载所有数据到内存。 - 该写法的逻辑和手写多层foreach循环完全等价,但代码结构更清晰,不容易出现层级遍历错误。
内容的提问来源于stack exchange,提问作者H4p7ic
相关产品推荐
相关产品推荐

