AnyAndAll
Determines whether a sequence contains any elements and whether all elements of a sequence satisfy a condition. The normal 'All' method returns true when the sequence is empty.
Source
static class Extensions {
/// <summary>
/// Determines whether a sequence contains any elements and whether all elements of a sequence satisfy a condition.
/// </summary>
/// <typeparam name="T">The type of the elements of source.</typeparam>
/// <param name="source">An IEnumerable<T> that contains the elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if every element of the source sequence passes the test in the specified predicate and the sequence is not empty; otherwise, false.</returns>
public static bool AnyAndAll<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
bool result = false;
foreach (T item in source) {
result = true;
if (!predicate(item)) {
result = false;
break;
}
}
return result;
}
}
Example
int[] a = new [] {1, 2, 3};
int[] e = Array.Empty<int>();
Console.WriteLine(a.AnyAndAll(n => n > 0)); // True, not empty and all above 0
Console.WriteLine(a.AnyAndAll(n => n > 1)); // False, not empty and first value is not above 0
Console.WriteLine(e.AnyAndAll(n => n > 0)); // False, e is Empty
Console.WriteLine();
Console.WriteLine(a.All(n => n > 0)); // True, all above 0
Console.WriteLine(a.All(n => n > 1)); // False, first value is not above 0
Console.WriteLine(e.All(n => n > 0)); // True, e is Empty
Author: Fons Sonnemans
Submitted on: 24 mrt. 2022
Language: csharp
Type: System.Collections.Generic.IEnumerable<T>
Views: 2546