Como posso remover nós de um SiteMapNodeCollection?
Pergunta
Eu tenho um repetidor que lista todos os web.sitemap
páginas filhas em uma página ASP.NET.Isso é DataSource
é um SiteMapNodeCollection
.Mas não quero que minha página de formulário de registro apareça lá.
Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection
For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes
If n.Url = "/Registration.aspx" Then
Children.Remove(n)
End If
Next
RepeaterSubordinatePages.DataSource = Children
O SiteMapNodeCollection.Remove()
método lança um
NotSupportedException:"A coleção é somente leitura".
Como posso remover o nó da coleção antes de DataBinding o Repetidor?
Solução
Seu não deve precisar CType
Dim children = _
From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _
Where n.Url <> "/Registration.aspx" _
Select n
Outras dicas
Usando Linq e .Net 3.5:
//this will now be an enumeration, rather than a read only collection
Dim children = SiteMap.CurrentNode.ChildNodes.Where( _
Function (x) x.Url <> "/Registration.aspx" )
RepeaterSubordinatePages.DataSource = children
Sem Linq, mas utilizando .Net 2:
Function IsShown( n as SiteMapNode ) as Boolean
Return n.Url <> "/Registration.aspx"
End Function
...
//get a generic list
Dim children as List(Of SiteMapNode) = _
New List(Of SiteMapNode) ( SiteMap.CurrentNode.ChildNodes )
//use the generic list's FindAll method
RepeaterSubordinatePages.DataSource = children.FindAll( IsShown )
evitar a remoção de itens de coleções como isso é sempre lento. A menos que você estiver indo para ser um loop através de várias vezes você é melhor fora de filtragem.
Eu tenho que trabalhar com código abaixo:
Dim children = From n In SiteMap.CurrentNode.ChildNodes _
Where CType(n, SiteMapNode).Url <> "/Registration.aspx" _
Select n
RepeaterSubordinatePages.DataSource = children
Existe uma maneira melhor, onde eu não tenho que usar o CType()
?
Além disso, isso define as crianças a um System.Collections.Generic.IEnumerable(Of Object)
. Existe uma boa maneira de voltar algo mais fortemente tipado como um System.Collections.Generic.IEnumerable(Of System.Web.SiteMapNode)
ou ainda melhor um System.Web.SiteMapNodeCollection
?