1.向下查询
/// <summary>
/// --1.指定ID ,向下查询所有的子节点------递归获取
/// </summary>
/// <param name="id"></param>
public List<Tree> getChild(int id)
{
List<Tree> list = new List<Tree>();
//根据NodeID,获取当前子节点列表
List<Tree> chidList = _Context.Trees.Where(q => q.ParentID == id).ToList();
if (chidList.Count > 0)
{
//获取下一级
list.AddRange(chidList);
foreach (var item in chidList)
{
//递归获取下一级
chidList = getChild(item.NodeID);
list.AddRange(chidList);
}
}
return list;
}
/// <summary>
/// --1.指定ID ,向下查询所有的子节点----死循环获取
/// </summary>
/// <param name="id"></param>
public List<Tree> getChild2(int id)
{
List<Tree> list = new List<Tree>();
List<int> idList = new List<int>() { id };
while (true)
{
//1.获取子节点列表
List<Tree> childList = _Context.Trees.Where(q => idList.Contains(q.ParentID)).ToList();
if (childList.Count <= 0)
break;
list.AddRange(childList);
//2.遍历子节点 ID列表
idList = childList.Select(q => q.NodeID).ToList();
if (idList.Count <= 0)
break;
}
return list;
}
2.向上查询
/// <summary>
/// --2.指定ID,向上查询所有的父级节点----递归获取
/// </summary>
public List<Tree> getParent(int id)
{
List<Tree> list = new List<Tree>();
//获取当前项
Tree tree = _Context.Trees.Where(q => q.NodeID == id).FirstOrDefault();
if (tree != null)
{
//获取上一级
Tree parent = _Context.Trees.Where(q => q.NodeID == tree.ParentID).FirstOrDefault();
if (parent != null)
{
list.Add(parent);
//递归调用 获取上一级
list.AddRange(getParent(parent.NodeID));
}
}
return list;
}
/// <summary>
/// --2.指定ID,向上查询所有的父级节点----死循环获取
/// </summary>
public List<Tree> getParent2(int id)
{
List<Tree> list = new List<Tree>();
while (true)
{
//1.获取当前项
Tree tree = _Context.Trees.Find(id);
if (tree == null)
break;
//2.修改下一次获取上一级
list.Add(tree);
id = tree.ParentID;
}
return list;
}
3.获取其他同级节点
/// <summary>
/// --3,指定ID,获取其他同级节点
/// </summary>
public List<Tree> getSiblings(int id)
{
List<Tree> list = new List<Tree>();
//1.获取当前项的上级ID
Tree tree = _Context.Trees.Find(id);
if (tree != null)
{
//2.获取上一级下的所有节点,过滤掉自己
list.AddRange(_Context.Trees.Where(q => q.ParentID == tree.ParentID && q.NodeID != id));
}
return list;
}
4.是否是子节点
/// <summary>
/// --3.指定ParentID,判断TargetID,是否是子节点
/// </summary>
public bool isChild(int parentID, int targetID)
{
//1.过滤 相同情况
if (parentID == targetID) return false;
List<int> idList = new List<int>() { parentID };
while (true)
{
//2.获取子节点列表
List<Tree> childList = _Context.Trees.Where(q => idList.Contains(q.ParentID)).ToList();
if (childList.Count <= 0)
return false;
//3.判断是否是子节点
if (childList.Any(q => q.NodeID == targetID))
return true;
//4.重置子节点ID 列表
idList = childList.Select(q => q.NodeID).ToList();
}
}
5.是否是父节点
/// <summary>
/// --4.指定ChildID,判断TargetID,是否是父节点
/// </summary>
public bool isParent(int childID, int targetID)
{
//1.过滤相同情况
if (childID == targetID) return false;
while (true)
{
//1.获取当前项
Tree tree = _Context.Trees.Find(childID);
if (tree == null)
return false;
//2.判断是否是父节点
if (tree.ParentID == targetID)
return true;
//3.重置字节ID
childID = tree.ParentID;
}
}