我有这样的界面:
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)
现在用户选择了他想要选择的元素以及我不希望能够返回所有选定元素的树,但此属性仅返回元素的第一层:
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
如何只返回此树/列表中选定的子元素?
正如评论中所指出的,我无法改变孩子(ReadOnly) 所以我的想法就是在界面中使用属性“selectedChilds”
这可能吗? 我看到的问题是在接口中我不能直接实现属性,我不喜欢我看到的其他选项: 具有已实现属性selectedChilds的抽象类 - >我不喜欢那样,因为如果我每次都这样做的话...... 每次实现界面时自己实现属性 - >我不喜欢这样,因为我会在CodeClones上使用CodeClone:/
答案 0 :(得分:1)
如果我理解正确,您希望获得所有选定的父母和所有选定的孩子。您可以使用递归方法:
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)
来支持理论上的无限深度。