ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

All() and Any() on Array and List<T>

Faster implementations of the LINQ All() and Any() methods for Array and List<T>. This solution uses less memory allocations and is just faster. Temporary solution until this PR is accepted https://github.com/dotnet/runtime/pull/1832

Source

public static class ArrayAndListExtensions {

    public static bool All<T>(this T[] array, Func<T, bool> predicate) {
        foreach (var item in array) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }

    public static bool All<T>(this List<T> list, Func<T, bool> predicate) {
        for (var i = 0; i < list.Count; i++) {
            if (!predicate(list[i])) {
                return false;
            }
        }
        return true;
    }

    public static bool Any<T>(this T[] array, Func<T, bool> predicate) {
        foreach (var item in array) {
            if (predicate(item)) {
                return true;
            }
        }
        return false;
    }

    public static bool Any<T>(this List<T> list, Func<T, bool> predicate) {
        for (var i = 0; i < list.Count; i++) {
            if (predicate(list[i])) {
                return true;
            }
        }
        return false;
    }

}

Example

int[] numbers = new int[100_000];

bool b = numbers.All(n => n == 0);

var sw = System.Diagnostics.Stopwatch.StartNew();

b = numbers.All(n => n == 0);

sw.Stop();
Console.WriteLine(sw.Elapsed);

Author: Fons Sonnemans

Submitted on: 7 feb 2020

Language: csharp

Type: Array and List<T>

Views: 3021