如何删除递归嵌套列表中的重复项

时间:2017-07-19 13:10:30

标签: c# list linq recursion

以下是我正在尝试实现的代码示例:

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

1 个答案:

答案 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);
    }
}