tags:

views:

42

answers:

2

I want to do

var testData = new[] { "aap", "aal", "noot", "mies", "wim", "zus", "jet" };
bool result = testData.Or(s => s.Contains("z"));

but there is no 'Or' method on IEnumerable.

I've tried programming an Or extension method using

public static class extensions
{
    public static bool Or<TSource>(this IEnumerable<TSource> sourceCollection, Func<TSource, bool> selector)
    {
        return sourceCollection.Where(selector).Select(selector).FirstOrDefault();
    }
}

Ofcourse, the idea is not to call selector() more often than necessary. The first call evaluating to true determines the result. The problem with my solution is that selector() is called twice on the first item that returns true. I imagine this is because of the call to Select().

How do I fix this?

+1  A: 
var testData = new[] { "aap", "aal", "noot", "mies", "wim", "zus", "jet"};
bool result = testData.Any(s => s.Contains("z"));

This will stop evaluation at the first match, as you want.

AakashM
Ah, yes! It's that simple! \Thanks
H. den Breejen
+1  A: 

I'm not sure I understood your problem but does the Linq extension method Any do what you're trying to achieve ?

gissolved