如何基于List<PropertyA>和List<PropertyB>生成新列表并处理重复值
解决方案
你遇到的问题核心是listB中同Name的多个Value需要按出现顺序,依次匹配listA中同Name的多个条目,普通嵌套遍历要么只能取第一个匹配值,要么只能取最后一个匹配值,无法满足多对多顺序匹配的要求。
可以通过预处理listB为「Name对应Value队列」的字典实现需求,完整实现代码如下:
步骤1:预处理listB生成分组队列
// 按Name分组,将同Name的Value按出现顺序存入队列,先进先出保证匹配顺序 Dictionary<string, Queue<string>> nameValueQueue = new Dictionary<string, Queue<string>>(); foreach (PropertyB propB in listB) { if (!nameValueQueue.ContainsKey(propB.Name)) { nameValueQueue[propB.Name] = new Queue<string>(); } nameValueQueue[propB.Name].Enqueue(propB.Value); }
步骤2:遍历listA生成新列表
List<PropertyB> newList = new List<PropertyB>(); foreach (PropertyA propA in listA) { PropertyB newProp = new PropertyB(); newProp.Name = propA.DisplayName; // 匹配到对应Name的队列,且队列还有值时,按顺序取第一个可用Value if (nameValueQueue.TryGetValue(propA.Name, out Queue<string> queue) && queue.Count > 0) { newProp.Value = queue.Dequeue(); } newList.Add(newProp); }
步骤3:输出验证
foreach (var item in newList) { Console.WriteLine($"{item.Name} {item.Value}"); }
最终输出完全符合预期:
LOB test789 ABC test234 DEF test123 GHI null Line of Business test456
该方案时间复杂度为O(n+m)(n为listA长度,m为listB长度),比嵌套循环的O(n*m)效率更高,同时能严格保证匹配顺序、不丢失数据。
内容的提问来源于stack exchange,提问作者wseipel
相关产品推荐
相关产品推荐

