When using the Link collection property in EPiServer CMS I often find my self needing to convert it’s values, that is a collection of LinkItems, into a list of PageData objects. Of course we can’t trust that all of the items are really links to local pages on the site, unless we use some custom property, so I must first check that each item can be mapped to a local page before trying to add it to the list. Luckily, some time ago I wrote a simple utility function for doing just that. Or, more likely, I picked it up on the EPiServer World forum and customized it a bit :)
Anyhow, I’ve been meaning to post this little utility function for quite some time now, and now I’ve finally gotten around to it.
The method is an extension method for the LinkItemCollection class and returns an ordered list of all items in the collection that can be mapped to local pages “converted” to PageData objects. I’ve removed the namespace for brevity.
using System.Collections.Generic;
using EPiServer;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.Web;
public static class LinkItemCollectionUtility
{
public static List<PageData> ToPages(this LinkItemCollection linkItemCollection)
{
List<PageData> pages = new List<PageData>();
foreach (LinkItem linkItem in linkItemCollection)
{
string linkUrl;
if (!PermanentLinkMapStore.TryToMapped(linkItem.Href, out linkUrl))
continue;
if (string.IsNullOrEmpty(linkUrl))
continue;
PageReference pageReference = PageReference.ParseUrl(linkUrl);
if (PageReference.IsNullOrEmpty(pageReference))
continue;
pages.Add(DataFactory.Instance.GetPage((pageReference)));
}
return pages;
}
}
PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.
This blog is built with EPiServer Community, EPiServer CMS, ASP.NET MVC and a bunch of other great products. The source code is available for download at the projects page, where you also can read more about this site and my other projects.
read more
Comments
Frederik Vig 1 years ago
I did something similar, but to a PageDataCollection: http://www.frederikvig.com/2009/06/episerver-extension-methods-part-2/.
Ted Nyberg 1 years ago
Great snippet! I like both approaches (both yours and Frederik's), but since I pretty much have a crush on generic lists I'm leaning towards yours... :) Although, as Frederik points out, having a PageDataCollection object helps in using some of the EPiServer API's methods since they accept the PageDataCollection type as the parameter.
Peter 11 months ago
Thanks! Exactly what I was looking for :)
Daniel Saidi 20 days ago
Great post! Just what we were looking for.