System.Linq.Enumerable.Any Method
public static bool Any(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
Determines whether any element of a sequence satisfies a condition.
Note: This is an extension method and can be called directly on an instance of the enumerable type. However, it is called using Enumerable.Any(source, predicate)
if you are not in a context where the extension method has been imported or is not available.
Parameters
Name | Type | Description |
---|---|---|
source |
IEnumerable<TSource> |
An IEnumerable<T> whose elements to apply the predicate to. |
predicate |
Func<TSource, bool> |
A function to test each element for a condition. |
Return Value
true
if any element of the source sequence passes the test in the specified predicate, or false
otherwise. If the sequence is empty, false
is returned.
Examples
Example 1: Checking for existence of a specific value
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Check if the list contains the number 3
bool hasThree = numbers.Any(n => n == 3);
Console.WriteLine($"Does the list contain 3? {hasThree}"); // Output: Does the list contain 3? True
// Check if the list contains the number 6
bool hasSix = numbers.Any(n => n == 6);
Console.WriteLine($"Does the list contain 6? {hasSix}"); // Output: Does the list contain 6? False
}
}
Example 2: Checking for existence of an element matching a more complex condition
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<string> words = new List<string> { "apple", "banana", "cherry", "date" };
// Check if any word starts with the letter 'b'
bool startsWithB = words.Any(w => w.StartsWith("b"));
Console.WriteLine($"Are there any words starting with 'b'? {startsWithB}"); // Output: Are there any words starting with 'b'? True
// Check if any word has a length greater than 7
bool longWordExists = words.Any(w => w.Length > 7);
Console.WriteLine($"Is there any word with length greater than 7? {longWordExists}"); // Output: Is there any word with length greater than 7? False
}
}
Example 3: Using Any on an empty list
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> emptyList = new List<int>();
// Calling Any on an empty list will always return false
bool anyElement = emptyList.Any(x => true);
Console.WriteLine($"Any element in an empty list? {anyElement}"); // Output: Any element in an empty list? False
}
}
Tip: The Any()
method overload without a predicate overload can be used to simply check if a sequence contains any elements at all.
bool hasElements = myList.Any();