简体   繁体   English

c#如何递归删除对象及其子项

[英]c# How to Recursively delete objects and its children

This is my function that gives me a list of nodes based on its parentId:这是我的函数,它根据其 parentId 为我提供节点列表:

public List<RepositoriesListViewModel> GetChildren(string ParentId)
{
    List<RepositoriesListViewModel> data = new List<RepositoriesListViewModel>();
    List<RepositoriesListViewModel> initialData = new List<RepositoriesListViewModel>();
    var List = dbContext.Repositories.ToList();
    foreach (var item in List)
    {
        initialData.Add(new RepositoriesListViewModel
        {
            id = item.Id,
            parent = item.ParentId,
            ApplicationsId = item.ApplicationsId,
            text = item.Name,
            Path = item.Path,
            CreatedOn = item.CreatedOn
        });
    };
    foreach (RepositoriesListViewModel child in initialData.Where(x => x.parent == ParentId))
    {
        child.Children = GetChildren(child.id);
        data.Add(child);
    }
    return data;
}

I was wondering if it were possible to delete an item and its children using this function as well?我想知道是否可以使用此功能删除项目及其子项? Where would I add my delete call?我应该在哪里添加我的删除电话?

This is what my delete call looks like:这是我的删除调用的样子:

public void Delete(string Input)
{
    try
    {
        var repo = Get(Input);
        dbContext.Repositories.Remove(repo);
        dbContext.SaveChanges();
        logger.LogInformation(LoggingGlobals.Delete + " Repository: " + repo.Name);
    }
    catch (Exception e)
    {
        logger.LogError(e, "Failed to delete Repository");
    }
}

It seems you want something like this:看来你想要这样的东西:

public void Delete(string Input)
{
    try
    {
        var children = GetChildren(Input);

        foreach(var child in children)
        {
            Delete(child.Id);
        }

        var repo = Get(Input);
        dbContext.Repositories.Remove(repo);
        dbContext.SaveChanges();
        logger.LogInformation(LoggingGlobals.Delete + " Repository: " + repo.Name);
    }
    catch (Exception e)
    {
        logger.LogError(e, "Failed to delete Repository");
    }
}

So Before you delete the item itself, you first delete its children and their children.因此,在删除项目本身之前,首先要删除其子项及其子项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM