Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# All Method

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

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. It returns true or false.

Extension Method

Example. To begin, include the System.Linq namespace. 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).


C# program that uses All method

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);




Benefits. 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

Note: Performance is usually more important than fancy syntax. This depends on the program.

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 MethodStatic Method