【问题标题】:How can I remove nodes from a SiteMapNodeCollection?如何从 SiteMapNodeCollection 中删除节点?
【发布时间】:2010-09-05 22:52:03
【问题描述】:

我有一个Repeater,它列出了ASP.NET 页面上的所有web.sitemap 子页面。它的DataSourceSiteMapNodeCollection。但是,我不希望我的注册表单页面出现在那里。

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

SiteMapNodeCollection.Remove() 方法抛出一个

NotSupportedException:“集合是只读的”。

如何在 DataBinding 中继器之前从集合中删除节点?

【问题讨论】:

    标签: asp.net .net vb.net repeater sitemap


    【解决方案1】:

    我让它与下面的代码一起工作:

    Dim children = From n In SiteMap.CurrentNode.ChildNodes _
                   Where CType(n, SiteMapNode).Url <> "/Registration.aspx" _
                   Select n
    RepeaterSubordinatePages.DataSource = children
    

    有没有更好的方法让我不必使用CType()

    此外,这会将孩子设置为System.Collections.Generic.IEnumerable(Of Object)。有没有一种好方法可以找回像System.Collections.Generic.IEnumerable(Of System.Web.SiteMapNode) 甚至更好的System.Web.SiteMapNodeCollection 这样的强类型?

    【讨论】:

      【解决方案2】:

      你不应该需要 CType

      Dim children = _
          From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _
          Where n.Url <> "/Registration.aspx" _
          Select n
      

      【讨论】:

        【解决方案3】:

        使用 Linq 和 .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 
        

        没有 Linq,但使用 .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 )
        

        避免从集合中删除项目,因为这总是很慢。除非您要循环多次,否则最好不要过滤。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-12
          • 2011-02-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多