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.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • LinkedIn
  • Ping.fm
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
kick it on DotNetKicks.com
Saturday, February 14th, 2009 Coding

3 Comments to Custom LINQ Operator?

  • Scott Allen says:

    Very cool. There is an “Any” operator with LINQ that takes a predicate and returns bool – the wording can feel odd in some scenarios though.

  • Dmitry says:

    How is it any different from the Any() operator?

    And don’t use Predicate, Comparison delegates. They are unofficially deprecated and should be replaced with Func and Action . It would be “bool Contains(…, Func predicate)” in the case of your operator.

  • iLude says:

    @Dmitry – How is it any different from the Any() operator?

    It’s not really, but as Scott Allen stated “The wording can feel odd…” which is the only reason I did it. Thanks for the tip on Func I’ll update my code and try it out.