Determines whether any element of a sequence satisfies a condition.
Method | Description |
---|---|
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) |
Tests whether any element of the |
public static bool Any<TSource>(this IEnumerable<TSource> source) |
Tests whether any element of the |
source
<TSource>IEnumerable<TSource>
to check for elements.predicate
<TSource, bool>true
if any elements in the source sequence pass the test in the specified predicate, or if there are any elements in the sequence; otherwise, false
.
TheAny
method iterates through the sequence and applies the transform in delegatepredicate
to each element. If the predicate function returnstrue
for any element in the sequence,Any
immediately returnstrue
. If the predicate function returnsfalse
for all elements in the sequence,Any
returnsfalse
. If the sequence is empty,Any
returnsfalse
.
If the sequence is empty and no predicate is specified,Any
returnsfalse
. If the sequence has at least one element and no predicate is specified,Any
returnstrue
.
This method uses deferred execution.
int[] numbers = { 1, 5, 3, 2, 10 };
bool hasEvenNumber = numbers.Any(n => n % 2 == 0);
// hasEvenNumber will be true
string[] fruits = { "apple", "banana", "cherry" };
bool hasAnyFruit = fruits.Any();
// hasAnyFruit will be true
string[] emptyArray = { };
bool hasAnyElement = emptyArray.Any();
// hasAnyElement will be false
This method can be called as an extension method on any object of type IEnumerable<TSource>
.