我在ObservableCollection中有一个项目的单子列表。这些项目具有属性item.Id和item.Parent.Id。 我已经得到父(顶级)的ID,现在用这个ID我需要遍历列表,并找到这个父母的孩子。每个孩子只能有一个父母,父母可以有多个孩子。从单位名单中获取子女
我该如何有效地做到这一点?
我在ObservableCollection中有一个项目的单子列表。这些项目具有属性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));
嗯,我知道了,但是,如果任何人都可以优化/重构这个代码转换成一些更有效的,请让我知道,我会标记为一个答案,你的反应。只要我学习:)。
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将包含顶层父+它包含了所有孩子的第一个项目。
对不起,忘了把这个放在我的描述中,但事情是,父母的孩子也可以包含他们自己的孩子等等。 – tutu
这只是让孩子在一个级别。孩子可以包含他们自己的孩子等,这段代码不会得到它们。至少我认为它没有或者我做错了什么? – tutu
@tutu编辑显示一种方法来处理此... –