获取树中具有特定字段值的元素列表

Get List of Elements in Tree with specific Field Value

我有这样的界面:

Public Interface TreeSelectorAttributes
    Property selectedInTreeSelector As Boolean
    Property Name As String
    ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes)
End Interface

我有一个 TreeView,其中有一个 TreeSelectorAttributes 列表:

Public Property rootList As IEnumerable(Of TreeSelectorAttributes)

现在,在用户选择了他想要 select 和不想要的元素之后,我希望能够 return 一棵包含所有 selected 元素的树,但是这个 属性只有return第一层元素:

Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes)
    Get
        Return (From ele As TreeSelectorAttributes
                In rootList
                Where ele.selectedInTreeSelector = True).ToList()
    End Get
End Property

我怎样才能 return 也只 selected child 这个 tree/list 中的元素?


正如评论中所指出的,我无法更改 childs(只读) 所以我的想法是在界面中有一个像 属性 "selectedChilds"

这可能吗? 我看到的问题是在一个接口中我不能直接实现 属性 而且我不喜欢我看到的其他选项: 有一个摘要 Class 和实现的 属性 selectedChilds -> 我不喜欢那样,因为如果我每次都这样做...... 每次实现接口时都自己实现 属性 -> 我不喜欢那样,因为我将拥有 CodeClones 而不是 CodeClones :/

如果我没理解错的话,你想要全部选中 parents 和全部选中 children。您可以使用递归方法:

Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes)
    Get
        Return rootList.Where(Function(t) t.SelectedInTreeSelector).
            SelectMany(Function(root) GetSelectedChildren(root)).
            ToList()
    End Get
End Property

Function GetSelectedChildren(root As TreeSelectorAttributes, Optional includeRoot As Boolean = True) As List(Of TreeSelectorAttributes)
    Dim allSelected As New List(Of TreeSelectorAttributes)
    If includeRoot Then allSelected.Add(root)
    Dim childTrees As New Queue(Of TreeSelectorAttributes)
    childTrees.Enqueue(root)
    While childTrees.Count > 0
        Dim selectedChildren = From c In childTrees.Dequeue().Children
                               Where c.SelectedInTreeSelector
        For Each child In selectedChildren
            allSelected.Add(child)
            childTrees.Enqueue(child)
        Next
    End While
    Return allSelected
End Function

此方法使用Queue(Of T)支持理论上无限深度。