Public NotInheritable Class LegendExtension Private Sub New() End Sub <System.Runtime.CompilerServices.Extension> _ Public Shared Function SelectedItems(legend As Legend) As IEnumerable(Of LegendItemViewModel) If legend Is Nothing Then Return Nothing End If Return legend.LayerItems.Descendants().Where(Function(item) item.IsSelected) End Function <System.Runtime.CompilerServices.Extension> _ Private Shared Function Descendants(layerItems As IEnumerable(Of LayerItemViewModel)) As IEnumerable(Of LegendItemViewModel) Dim result As New List(Of LegendItemViewModel)() If layerItems Is Nothing Then Return result End If For Each layerItem As var In layerItems result.Add(layerItem) ' return legend items If layerItem.LegendItems IsNot Nothing Then result.AddRange(layerItem.LegendItems) End If ' return recursively layer items If layerItem.LayerItems IsNot Nothing Then result.AddRange(layerItem.LayerItems.Descendants()) End If Next Return result End Function End Class