Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/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
.net 如何编写LINQ查询来执行递归?_.net_Linq - Fatal编程技术网

.net 如何编写LINQ查询来执行递归?

.net 如何编写LINQ查询来执行递归?,.net,linq,.net,Linq,如果我有一个名为Thing的对象,它有一个属性Id和Children,其中Children本质上是Thing的列表。它看起来是这样的: Public Class Thing Public Property Id As Guid Public Property Children As List(Of Thing) End Class 现在给定一个现有的列表(对象),为了这个示例,我们将其称为aList,如何使用LINQ递归地循环抛出每个对象和子对象,以确定整个层次结构中是否存在一

如果我有一个名为
Thing
的对象,它有一个属性
Id
Children
,其中
Children
本质上是
Thing
的列表。它看起来是这样的:

Public Class Thing
    Public Property Id As Guid
    Public Property Children As List(Of Thing)
End Class
现在给定一个现有的
列表(对象)
,为了这个示例,我们将其称为
aList
,如何使用LINQ递归地循环抛出每个对象和子对象,以确定整个层次结构中是否存在一个项

Dim List作为(事物的)列表

换句话说,给定一个ID,我如何针对
aList
编写LINQ语句,以查看该ID是否存在于层次结构中的任何位置


希望您能帮助我,并提前感谢您的贡献

Linq不是为递归而设计的,也不能很好地处理它。有很多方法可以限制它,但标准递归函数会更干净,更容易调试:

Public Function IsInTree(Thing theThing, IEnumerable(Of Thing) tree) As Boolean
    If tree.Any(Function(t) t.Id = theThing.Id) Then 
        IsInTree = True
    ElseIf Children Is Not Nothing Then
        IsInTree = tree.Any(Function(t) IsInTree(theThing, t.Children))
    Else
        IsInTree = False
    End If
End Function

编写一个递归函数,该函数接受要匹配的
IEnumerable
对象。您只想要VB解决方案吗?如果是这样的话,您应该添加标记。类似于
aList.single(function(x)x.Id=refId)
不是吗?我解决了一个问题。当它可用时,请看一看。