TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

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

PredicateBool

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

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

Output

True
False
True

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


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf