如何编写删除嵌套文件夹的递归函数

时间:2014-06-04 17:22:12

标签: c# linq

我有一项删除文件夹层次结构的任务。当我删除文件夹时,应删除相应的子文件夹。

public ActionResult DeleteLabel(int id)
        {
            var query = dbPanAgroDMSContext.LabelMaster.Where(x => x.ParentLabelId == id).ToList();
            foreach(var item in query)
            {
                var query1 = dbPanAgroDMSContext.LabelMaster.Where(x => x.ParentLabelId == item.LabelId).ToList();
                dbPanAgroDMSContext.LabelMaster.Remove(item);
                foreach (var i in query1)
                {
                    dbPanAgroDMSContext.LabelMaster.Remove(i);
                }
            }
            LabelMaster label = dbPanAgroDMSContext.LabelMaster.Find(id);
            dbPanAgroDMSContext.LabelMaster.Remove(label);
            dbPanAgroDMSContext.SaveChanges();
            return Json(new { Result = "OK" });
        }

我没有使用重复的for循环,而是想在一个代码块中执行它。请帮我创建一个linq查询?

1 个答案:

答案 0 :(得分:1)

试试这个

public ActionResult DeleteLabel(int id)
        {
            Delete(id);
            dbPanAgroDMSContext.SaveChanges();
            return Json(new { Result = "OK" });
        }
private void Delete(int id)
{
      //For given id get all child ones first            
          var query = dbPanAgroDMSContext.LabelMaster.Where(x => x.ParentLabelId == id).ToList();
            foreach(var item in query)
            {
                     //for each child ,delet its' childs by calling recursively
                    Delete(item.Id);
            }
            LabelMaster label = dbPanAgroDMSContext.LabelMaster.Find(id);
            dbPanAgroDMSContext.LabelMaster.Remove(label);
}