从平面列表中获取孩子

时间:2011-12-12 20:43:42

标签: silverlight-4.0

我在ObservableCollection中有一个扁平的项目列表。这些项目具有item.Id和item.Parent.Id属性。 我已经获得了父级(顶级)的id,现在有了这个id,我需要遍历列表并找到这个父级的子级。每个孩子只能有一个父母,父母可以有多个孩子。

我该如何有效地做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用:

var childrenOfParent = theCollection.Where(item => item.Parent.Id == parentId);

编辑以回应评论:

鉴于你有一个分层数据集,我个人会做一个例程,检查一个给定的项目是否有一个特定的项目作为父项递归,如下所示:

bool HasParent(Item item, int parentId)
{
    if (item.Parent == null)
        return false;
    else if (item.Parent.Id == parentId)
        return true;
    else
        return HasParent(item.Parent, parentId);
}

鉴于此,您可以使用:

var childrenOfParent = theCollection.Where(item => HasParnet(item, parentId));

答案 1 :(得分:0)

嗯,我得到了它,但是,如果有人可以优化/重构这些代码更有效率请告诉我,我会将你的反应标记为答案。只要我学习:)。

        foreach (var item in myitemlist) // first put the top level parent in the queue
        {
            if (parentitem.Id == item.Id)
            {
                filteredChildrenQueue.Enqueue(item);
            }
        }

        while (!stillsearching)
        {
            if (filteredChildrenQueue.Count == 0)
            {
                stillsearching = true;

                return;
            }

            FindParentChild();
        }

继续调用此方法并处理队列中的第一项

    private void FindParentChild()
    {
        foreach (var item in myitemlist)
        {
            if (item.Parent.Id == filteredChildrenQueue.ElementAt(0).Id)
            {
                filteredChildrenQueue.Enqueue(item);
            }
        }

        filteredChildrenList.Add(filteredChildrenQueue.ElementAt(0));
        filteredChildrenQueue.Dequeue();
    }

filteredChildrenList将包含顶级父级+它包含的所有子级。