如何从SiteMapNodeCollection中删除节点?
时间:2020-03-05 18:39:52 来源:igfitidea点击:
我有一个Repeater,它列出了ASP.NET页上的所有" web.sitemap"子页。它的"数据源"是" SiteMapNodeCollection"。但是,我不想在此显示我的注册表表格页面。
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: "Collection is read-only".
在对数据转发器进行数据绑定之前,如何从集合中删除该节点?
解决方案
回答
使用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 )
避免从集合中删除项目,因为那总是很慢的。除非我们要遍历多次,否则最好不要进行过滤。
回答
我得到它与下面的代码一起使用:
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?
回答
我们不需要CType
Dim children = _ From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _ Where n.Url <> "/Registration.aspx" _ Select n