System.Linq
Class Enumerable
Method All
public static bool All<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
Summary
Determines whether all elements of a sequence satisfy a condition.
Type Parameters
TSource
- The type of the elements of
source
.
Returns
true
if all elements of the sequence satisfy the condition; otherwise, false
.
Exceptions
ArgumentNullException
source
orpredicate
is null.
Remarks
The All
method returns true
if the sequence is empty.
If the sequence is empty, the predicate
delegate is not invoked.
Usage Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int> { 2, 4, 6, 8, 10 };
bool allEven = numbers.All(n => n % 2 == 0);
Console.WriteLine($"All numbers are even: {allEven}"); // Output: All numbers are even: True
List<int> mixedNumbers = new List<int> { 1, 2, 3, 4, 5 };
bool allPositive = mixedNumbers.All(n => n > 0);
Console.WriteLine($"All numbers are positive: {allPositive}"); // Output: All numbers are positive: True
List<int> numbersWithNegative = new List<int> { 1, 2, -3, 4, 5 };
bool allPositiveAgain = numbersWithNegative.All(n => n > 0);
Console.WriteLine($"All numbers are positive: {allPositiveAgain}"); // Output: All numbers are positive: False
}
}