Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 在c中使用递归查找实体的最终父级#_Asp.net_C# 4.0_Recursion_Parent Child - Fatal编程技术网

Asp.net 在c中使用递归查找实体的最终父级#

Asp.net 在c中使用递归查找实体的最终父级#,asp.net,c#-4.0,recursion,parent-child,Asp.net,C# 4.0,Recursion,Parent Child,我有一个实体,它反过来引用同一个表,该表是它的父表。下表对其进行了更好的描述 | ID | Source_ID | +----+----------+ | 1 | null | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 4 | 现在,当我在ID=5时,我需要获取它的最终父对象,即ID=1 我尝试编写一个函数,如下所示: <entity> ultimateparententity;

我有一个实体,它反过来引用同一个表,该表是它的父表。下表对其进行了更好的描述

| ID | Source_ID |
+----+----------+
| 1  | null     |
| 2  | 1        |
| 3  | 1        |
| 4  | 2        |
| 5  | 4        |
现在,当我在ID=5时,我需要获取它的最终父对象,即ID=1

我尝试编写一个函数,如下所示:

<entity> ultimateparententity;
internal <entity> FetchParentComponentRecursive(<entity> entity)
 {
  if (component.ParentEntity!= null)
  {
     FetchParentComponentRecursive(entity.ParentEntity);
  }
  else
  {
     ultimateparententity = entity;
     return component;
  }
 return entity;
}
ultimateparententity;
内部FetchParentComponentRecursive(实体)
{
if(component.ParentEntity!=null)
{
FetchParentComponentRecursive(entity.ParentEntity);
}
其他的
{
最终父实体=实体;
返回组件;
}
返回实体;
}

我使用在类级别声明的变量来了解最终的父级。我返回变量“Entity”,以后再也不用它了,但使用的是ultimateparententity。这种方法有效,但我对此不太满意。任何方向都会有帮助

我不太熟悉C#,但是递归函数的一般结构看起来不太好

尝试以下几点:

internal <entity> FetchParentComponentRecursive(<entity> entity)
{
  if (component.ParentEntity == null)
  {
     return component;
  }
  else
  {
     return FetchParentComponentRecursive(entity.ParentEntity);
  }
}
内部FetchParentComponentRecursive(实体)
{
if(component.ParentEntity==null)
{
返回组件;
}
其他的
{
返回FetchParentComponentRecursive(entity.ParentEntity);
}
}

顺便说一下,这在很大程度上取决于数据集中没有循环引用。

数据库中没有循环引用。我将尝试这种方法。谢谢:)