Does Any () stop on success?

To be more specific: will the Linq extension method Any(IEnumerable collection, Func predicate)stop checking all remaining collection items as soon as the predicate gives true for the item?

Because I do not want to spend a lot of time figuring out whether I really need to do really expensive parts:

if(lotsOfItems.Any(x => x.ID == target.ID))
    //do expensive calculation here

So, if you Anyalways check all the elements in the source, this may turn out to be a waste of time, and not just:

var candidate = lotsOfItems.FirstOrDefault(x => x.ID == target.ID)
if(candicate != null)
     //do expensive calculation here

because I’m sure that it FirstOrDefaultreturns the result when it received the result, and only continues to go through the whole Enumerableif it does not find a suitable record in the collection.

Does anyone have information on internal functions Any, or can anyone suggest a solution for such a solution?

, - :

if(!lotsOfItems.All(x => x.ID != target.ID))

, false , , , - , .

+4
5

, :

 internal static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
            foreach (T element in source) {
                if (predicate(element)) {
                    return true; // Attention to this line
                }
            }
            return false;
        }

Any() - , LINQ.

: -

if (! lotsOfItems.All(x = > x.ID!= target.ID)), , false , , , - , : > ]

All() , . , , .

:
, Linq . Linq , .

+8

: https://ideone.com/nIDKxr

public static IEnumerable<int> Tester()
{
    yield return 1;
    yield return 2;
    throw new Exception();
}

static void Main(string[] args)
{
    Console.WriteLine(Tester().Any(x => x == 1));
    Console.WriteLine(Tester().Any(x => x == 2));

    try
    {
        Console.WriteLine(Tester().Any(x => x == 3));
    }
    catch
    {
        Console.WriteLine("Error here");
    }
}

, : -)

: -

if (! lotsOfItems.All(x = > x.ID!= target.ID))

, false , , , - , : > ]

, All() , false:-) , All() : -)

+3

, , .

IEnumerable :

foreach(var item in source)
  if(predicate(item))
    return true;
return false;

, :

using(var en = source.GetEnumerator())
  return en.MoveNext();

-

SELECT EXISTS(SELECT null FROM [some table] WHERE [some where clause])

. , , , , , WHERE, , , .

, Linq , , , .

, , FirstOrDefault, FirstOrDefault , (, ). !All(inversePredicate) Any(predicate) .

Single

. .NET Core, Single.

, linq-to Single SingleOrDefault, , . Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) :

public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
  /* do null checks */
  using(var en = source.GetEnumerator())
    while(en.MoveNext())
    {
      var val = en.Current;
      if(predicate(val))
      {
        while(en.MoveNext())
          if(predicate(en.Current))
            throw new InvalidOperationException("too many matching items");
        return val;
      }
    }
  throw new InvalidOperationException("no matching items");
}

- - :

public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    /* do null checks */
    var result = default(TSource);
    long tally = 0;
    for(var item in source)
        if(predicate(item))
        {
            result = item;
            checked{++tally;}
        }
    switch(tally)
    {
        case 0:
            throw new InvalidOperationException("no matching items");
        case 1:
            return result;
        default:
            throw new InvalidOperationException("too many matching items");
    }
}

, Single , , Single , , ( ), - , - , , , , Single, , .

SingleOrDefault .

linq-to-objects, .Where(predicate).Single() Single(predicate) .

+2

. .

I don’t know if the documentation guarantees, but this behavior is now effectively fixed all the time due to compatibility considerations. It also makes sense.

+1
source

Yes, it stops when the predicate is executed once. Here is the code using RedGate Reflector:

    [__DynamicallyInvokable]
    public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        if (predicate == null)
        {
            throw Error.ArgumentNull("predicate");
        }
        foreach (TSource local in source)
        {
            if (predicate(local))
            {
                return true;
            }
        }
        return false;
    }
+1
source

All Articles