【发布时间】:2016-03-29 16:56:04
【问题描述】:
我有以下格式的树结构数据:
H1
H1 - 1
H1 - 1 - 1
H1 - 1 - 1 - 1
H1 - 1 - 1 - 1 -1
H1 - 1 - 1 - 1 -1 - 1
H1 - 1 - 2
H1 - 1 - 3
H1 - 2
H1 - 2 - 1
H1 - 2 - 2
H2
H3
H3 - 1
H3 - 1 - 1
H3 - 1 - 1 - 1
H3 - 1 - 1 - 1 - 1
H3 - 1 - 1 - 2
H3 - 1 - 2
H3 - 1 - 3
H3 - 2
我必须通过传递子项的ID 来检查上述树中是否存在某个项目,因此我需要遍历上述树中的每个项目。到目前为止,我已经编写了以下递归方法:
public bool CheckIfChildItemExists(Item parentItem, long childItemId)
{
var isChildExisting = false;
foreach (Item item in parentItem.Children)
{
if (item == context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault() || item.Children.Contains(context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault()))
{
isChildExisting = true;
return isChildExisting;
}
else
{
return CheckIfChildItemExists(item, childItemId);
}
}
return isChildExisting;
}
使用上述方法:
- 根项目
H1, H2, H3可访问。 -
H1(H1 -1、H1 - 1 - 1、H1 - 1 - 1 -1等)的所有分支都可以访问。 -
H1 - 2 - 1和H1 - 2 - 2不可访问,它们没有被遍历。不过他们的父项H1 - 2是可以访问的。 -
H3的所有子代均不可访问。
我的方法做错了什么?
【问题讨论】:
-
看起来你的 List
不是单根/父,你必须处理这种情况。 -
@HariPrasad 我必须检查该项目是否存在于
parentItem的子代中,我将其传递给具有我在问题中提到的子数据的方法。H1, H2, H3是子项。
标签: c# entity-framework linq tree