C#中筛选嵌套对象列表中存在/不存在的Structure1对象
解决方案:对比不同结构对象列表并分类
错误代码问题分析
你原来的代码逻辑有两个核心问题:
- 每次匹配到一个
arr2.id就把整个Structure1数组全部加入foundList,反之加入notFoundList,导致所有对象被重复添加,最终结果完全错误。 - 没有先提取
ObjectsB中所有的id集合,而是嵌套循环逐个判断,既低效又逻辑混乱。
正确实现思路
先从多层嵌套的ObjectsBList中提取所有有效的id(转换为int类型),存入HashSet(查询效率远高于数组遍历),再逐个检查Structure1中的对象id是否在这个集合里,分别归类。
完整代码实现
// 1. 从ObjectsBList中提取所有有效的int类型id,去重存入HashSet var existingIds = new HashSet<int>(); foreach (var objB in ObjectsBList) { if (objB.array1 == null) continue; foreach (var arr1 in objB.array1) { if (arr1.array2 == null) continue; foreach (var arr2 in arr1.array2) { // 处理id转换异常,避免非数字字符串导致崩溃 if (int.TryParse(arr2.id, out int id)) { existingIds.Add(id); } } } } // 2. 遍历Structure1数组,分类到foundList和notFoundList var foundList = new List<Structure1>(); var notFoundList = new List<Structure1>(); if (ObjectAList.Structure1 != null) { foreach (var item in ObjectAList.Structure1) { if (existingIds.Contains(item.id)) { foundList.Add(item); } else { notFoundList.Add(item); } } }
关键细节说明
- HashSet的使用:HashSet的
Contains方法是O(1)时间复杂度,相比数组遍历的O(n),在数据量大时效率提升明显。 - 空值判断:加入了对
array1、array2的空值检查,避免空引用异常。 - 异常处理:用
int.TryParse代替Convert.ToInt32,防止arr2.id是无效数字字符串时程序崩溃。
内容的提问来源于stack exchange,提问作者Evelin Ramos
相关产品推荐
相关产品推荐

