C# All Method

All extension method

All is an extension method. It tells you if all the elements in a collection match a certain condition. It is part of the System.Linq namespace in the .NET Framework.

This C# program uses the All extension method from System.Linq.

Example

Note

To begin, make sure you have the System.Linq namespace included. Next, pass in a lambda expression to the All method. This lambda must receive one parameter (the type of element in the collection), and return one bool (whether it matches the condition or not).

Lambda Expression
Program that uses All method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 10, 20, 30 };

	// Are all elements >= 10? YES
	bool a = array.All(element => element >= 10);

	// Are all elements >= 20? NO
	bool b = array.All(element => element >= 20);

	// Are all elements < 40? YES
	bool c = array.All(element => element < 40);

	Console.WriteLine(a);
	Console.WriteLine(b);
	Console.WriteLine(c);
    }
}

Output

True
False
True
Question and answer

Benefits. So why would you ever use the All method instead of looping over elements and using an if-statement to test them? The All method is more compact; it is probably also slower due to the requirement that a Func instance be created.

Func Type

Summary

As part of the LINQ extensions to the C# language, the All method serves a very specific purpose. For arrays, you can also use the Array.TrueForAll method, which uses the same syntax but is a static method.

Array.TrueForAll Method LINQ
.NET