LINQ All

Summary: in this tutorial, you’ll learn how to use the LINQ All() method to determine if all elements of a sequence satisfy a specified condition.

Introduction to the LINQ All() method

The All() is an extension method in LINQ that returns true if all elements of a sequence satisfy a specified condition. Otherwise, it returns false.

bool ALL<TSource> (
   this IEnumerable<TSource> source, 
   Func<TSource,bool> predicate
);Code language: C# (cs)

In this syntax:

  • source is an input sequence with the type IEnumerable<T>.
  • predicate is a function that returns true if the element satisfies a condition.

LINQ All() examples

Let’s take some examples of using the All() extension method.

1) Using LINQ All() method to check if all elements of a sequence satisfy a condition

The following example demonstrates how to use the LINQ All() method to check if all elements of a sequence satisfy a condition:

using static System.Console;

int[] numbers = { 2, 4, 6, 8 };

bool allEvenNumbers = numbers.All(n => n % 2 == 0 ? true : false);

if (allEvenNumbers)
{
    WriteLine("All numbers are even.");
}Code language: C# (cs)

In this example, the lambda expression n => n % 2 == 0 ? true : false tests all numbers in the numbers array and returns true if all of them are even.

2) Using LINQ All() method with a sequence of objects

The following program demonstrates how to use the All() method to check if all employees have a salary greater than 40K:

using static System.Console;

namespace LINQDemo
{
    class Employee
    {
        public string? Name { get; set; }
        public string? Department { get; set; }
        public int Salary { get; set; }

    }
    class Program
    {
        public static void Main()
        {
            var employees = new List<Employee>() {
                new() { Name = "John", Department = "HR", Salary = 50000 },
                new() { Name = "Jane", Department = "IT", Salary = 60000 },
                new() { Name = "Bob",  Department = "HR", Salary = 45000 },
                new() { Name = "Sara", Department = "IT", Salary = 55000 },
                new() { Name = "Tom",  Department = "IT", Salary = 65000 }
            };

            var result = employees.All(e => e.Salary > 40000);
            if (result)
            {
                WriteLine("All employees have salary greater than 40000");
            }

        }
    }
}Code language: C# (cs)

Output:

All employees have salary greater than 40000Code language: plaintext (plaintext)

In this example, the lambda expression e => e.Salary > 40000 applies to each Employee object and returns true if all employees have a salary greater than 40000.

Summary

  • Use LINQ All() method to determine if all elements in a sequence satisfy a specified condition.
Was this tutorial helpful ?