Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Iterator<T>.TryGetFirst in Enumerable.Any() #99218

Merged
merged 1 commit into from
Mar 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions src/libraries/System.Linq/src/System/Linq/AnyAll.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections;
using System.Collections.Generic;

namespace System.Linq
Expand All @@ -9,15 +10,37 @@ public static partial class Enumerable
{
public static bool Any<TSource>(this IEnumerable<TSource> source)
{
return
TryGetNonEnumeratedCount(source, out int count) ? count != 0 :
WithEnumerator(source);
if (source is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}

static bool WithEnumerator(IEnumerable<TSource> source)
if (source is ICollection<TSource> gc)
{
using IEnumerator<TSource> e = source.GetEnumerator();
return e.MoveNext();
return gc.Count != 0;
}

#if !OPTIMIZE_FOR_SIZE
if (source is Iterator<TSource> iterator)
{
int count = iterator.GetCount(onlyIfCheap: true);
if (count >= 0)
{
return count != 0;
}

iterator.TryGetFirst(out bool found);
return found;
}
#endif

if (source is ICollection ngc)
{
return ngc.Count != 0;
}

using IEnumerator<TSource> e = source.GetEnumerator();
return e.MoveNext();
}

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Expand Down