以下是我正在尝试实现的代码示例:
int counter = 0;
var services = new List<Service>
{
new Service {Id = ++counter, Code = "SG1", Services = new List<Service>
{
new Service {Id = ++counter, Code = "S1"},
new Service {Id = ++counter, Code = "S2"},
new Service {Id = ++counter, Code = "S3"},
new Service {Id = ++counter, Code = "S4"},
new Service {Id = ++counter, Code = "S5"},
new Service {Id = ++counter, Code = "SG2",
Services = new List<Service>
{
new Service {Id = ++counter, Code = "S3"},
new Service {Id = ++counter, Code = "S4"},
new Service {Id = ++counter, Code = "S5"},
new Service {Id = ++counter,Code = "SG3",
Services = new List<Service>
{
new Service {Id = ++counter, Code = "S3"},
new Service {Id = ++counter, Code = "S4"},
}
}
}
}
}
}
};
我需要解决的输出如下:
SG1 -->S1 -->S2 -->SG1 ------>S5 ------>SG3
---------->S3 ---------->S4
答案 0 :(得分:3)
你通过深度优先遍历来实现。你不需要LINQ。
这是一些假代码,可以让您了解如何做到这一点:
public static void RemoveDuplicates(Service service) {
var toRemove = new HashSet<string>();
RemoveDuplicates(service, toRemove);
}
private static void RemoveDuplicates(Service service, ISet<string> toRemove) {
// Collect all child codes, and clean up children in the process
foreach (var child in services) {
RemoveDuplicates(child, toRemove);
}
// Remove all child codes from self
foreach (var code in toRemove) {
service.RemoveCode(code);
}
// Add the remaining codes for my parents to remove
foreach (var myCode in allMyCodes) {
toRemove.Add(myCode);
}
}