System.Linq.Enumerable.All Method

public static bool All<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)

Summary

Determines whether all elements of a sequence satisfy the specified condition.

Parameters

Returns

bool

true if every element of the sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

Exceptions

Remarks

The All method returns true if the sequence is empty. This is because no element fails the condition.

The All method performs deferred execution.

The predicate parameter must not be null.

Examples

The following code example demonstrates how to use the All method to determine if all elements in an array of integers are even.

using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main()
    {
        int[] numbers1 = { 2, 4, 6, 8 };
        int[] numbers2 = { 2, 4, 5, 8 };

        bool allEven1 = numbers1.All(n => n % 2 == 0);
        bool allEven2 = numbers2.All(n => n % 2 == 0);

        Console.WriteLine("All numbers in numbers1 are even: {0}", allEven1);
        Console.WriteLine("All numbers in numbers2 are even: {0}", allEven2);

        // Example with an empty collection
        List<int> emptyList = new List<int>();
        bool allInEmptyAreEven = emptyList.All(n => n % 2 == 0);
        Console.WriteLine("All numbers in an empty list are even: {0}", allInEmptyAreEven);
    }
}

Output:

All numbers in numbers1 are even: True
All numbers in numbers2 are even: False
All numbers in an empty list are even: True

Extension methods

This method is defined as an extension method for IEnumerable<TSource>. You can call it directly on an instance of the type.

LINQ to Objects Information

This method is implemented using deferred execution.

Related methods