Custom LINQ Operator?

K. Scott Allen has a great post up titled Why Would I Create A Custom LINQ Operator? I figured I’d add my minor addition to the discussion.

public static bool Contains<T>(this IEnumerable<T> enumerator, Predicate<T> predicate)
{
    if(enumerator == null)
        throw new ArgumentNullException("enumerator");
    if(predicate == null)
        throw new ArgumentNullException("predicate");
    foreach(T item in enumerator)
    {
        if(predicate(item))
            return true;
    }
    return false;
}

 

This allows you to do this:

if(tags.Contains(x => x.Name == "Coolest Blog Ever")) {
    // we found a matching tag
}
else {
    // no tag found :-( 
}

 

Nothing special I know, but hopefully it helps someone out.

kick it on DotNetKicks.com
Saturday, February 14th, 2009 Coding

Leave a Reply

Blog WebMastered by All in One Webmaster.

WP SlimStat