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.
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.
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.
@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.