Silverlight 4.0 从平面列表中获取孩子

Silverlight 4.0 从平面列表中获取孩子,silverlight-4.0,Silverlight 4.0,我在一个可观察的集合中有一个简单的项目列表。这些项具有item.Id和item.Parent.Id属性。 我已经得到了父级(顶层)的id,现在有了这个id,我需要遍历列表并找到父级的子级。每个子级只能有一个父级,一个父级可以有多个子级 如何有效地执行此操作?您可以使用: var childrenOfParent = theCollection.Where(item => item.Parent.Id == parentId); 根据评论进行编辑: 假设您有一个分层数据集,我个人会做一个

我在一个可观察的集合中有一个简单的项目列表。这些项具有item.Id和item.Parent.Id属性。 我已经得到了父级(顶层)的id,现在有了这个id,我需要遍历列表并找到父级的子级。每个子级只能有一个父级,一个父级可以有多个子级

如何有效地执行此操作?

您可以使用:

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));

我明白了,不过,如果有人能优化/重构这段代码,使之更高效,请让我知道,我会记下你的反应作为答案。只要我学会:)

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

    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将包含顶级父级+它包含的所有子级。

很抱歉,我忘了在我的描述中添加这一点,但问题是,父级的子级也可以包含自己的子级,依此类推。这仅获取一个级别的子级。Childs可以包含自己的Childs等等,而这段代码没有得到它们。至少我认为没有,或者我做错了什么?
    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();
    }