Predicate based filter for EPiServer

by aanund 17. July 2010 01:06

Today I needed to do some basic filtering of a PageDataCollection in a new EPiServer site. And I thought I would hack together a simple IPageFilter to do the job.

Then it occurred to me that this would be easy to handle if using LINQ. So I took a look a what I had just created and decided to rewrite it instead.

public class PredicateFilter : IPageFilter
{
    private readonly Predicate<PageData> _predicate;

    public PredicateFilter(Predicate<PageData> predicate)
    {
        _predicate = predicate;
    }

    public void Filter(object sender, FilterEventArgs e)
    {
        Filter(e.Pages);
    }

    public void Filter(PageDataCollection pages)
    {
        for (int i = pages.Count - 1; i >= 0; i--)
        {
            if (ShouldFilter(pages[i]))
            {
                pages.RemoveAt(i);
            }
        }
    }

    public bool ShouldFilter(PageData page)
    {
        return _predicate(page);
    }
}

Usage is something like this.

new PredicateFilter(p => p["PageShortcutLink"] != null).Filter(pages);
Bookmark and Share

About me

I work for EDB Consulting Group in Oslo, Norway.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010