递归地将树结构添加到List C#

时间:2013-10-16 08:05:00

标签: c# recursion neo4jclient

所以我有一些代码执行Neo4j cypher查询,返回IEnumerable类型FolderObject,如下所示:

public IEnumerable<FolderObject> GetChild(string parentId)
{
    IEnumerable<FolderObject> childNode = null;
    var query = GraphConnection.Cypher
    .Start(new { n = Node.ByIndexLookup("node_auto_index", "ObjectId", parentId) })
    .Match("(n)-[r:HAS_FOLDER]->(b)")
    .Where("b.ParentId = n.ObjectId")
    .Return<FolderObject>("b");

    childNode = query.Results;

    return childNode;
}

FolderObject看起来像这样:

public string ObjectId { get; set; }
public string ParentId {get; set;}
public List<GraphObject> Children { get; set; }

然后我有这个方法可以正常工作:

public List<FolderObject> GetChildren(string repositoryId, string folderId)
{
    List<FolderObject> items;

    QueryOperations query = new QueryOperations(GraphConnection);

    var queryResult = query.GetChild(folderId);

    string childId = null;

    if (queryResult != null)
    {
        foreach (var item in queryResult)
        {
            childId = item.ObjectId;

            items = new List<FolderObject>();

            items.Add(item);

            var nextChild = GetChildren(repositoryId, childId);
        }
    }
    else
    {
        throw new Exception("The Folder with Id: " + folder + " could not be found.");
    }

    return items
}

现在,当我尝试以递归方式执行此操作时问题就出现了。我需要做的是将最顶层的文件夹添加到列表中,然后获取最顶层的下一个文件夹,并将其作为子项添加。然后重复,直到没有更多的孩子。

结构如下:

-Folder
    -Folder
        -Folder
            -Folder

并将此结构作为List返回?

这是Json

{
    "ParentId": "0",
    "ObjectId": "1",
    "children": [
        {
            "ParentId": "1",
            "ObjectId": "2",
            "children": [
                {
                    "ParentId": "2",
                    "ObjectId": "3"
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:2)

你可以使用类似于递归方法的Stack<FolderObject>,唯一的区别是它不是递归的。 Imho它更具可读性和复杂性。

public List<FolderObject> GetChildren(string repositoryId, string folderId)
{
    List<FolderObject> items = new List<FolderObject>();;

    QueryOperations query = new QueryOperations(GraphConnection);
    var queryResult = query.GetChild(folderId);

    Stack<FolderObject> folders = new Stack<FolderObject>(queryResult);

    while (folders.Count > 0)
    {
        FolderObject currentFolder = folders.Pop();
        var childId = currentFolder.ObjectId;
        items.Add(currentFolder);
        var nextChildren = GetChildren(repositoryId, childId);
        foreach (FolderObject child in nextChildren)
            folders.Push(child);
    }

    return items;
}