3

所以我有一些代码可以执行 Neo4j 密码查询,该查询返回如下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

并将此结构作为列表返回?

这是Json

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

1 回答 1

2

您可以使用Stack<FolderObject>类似于递归方法的 a ,唯一的区别是它不是递归的。恕我直言,它更具可读性且不那么复杂。

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;
}
于 2013-10-16T08:22:21.130 回答