C# All Method: All Elements Match a Condition

This C# program uses the All extension method from System.Linq. All returns true if all elements match a condition.
All. This is an extension method. It tells us 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.
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).LINQExtensionPredicateBool
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

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 specific purpose. For arrays, you can also use the Array.TrueForAll method, which uses the same syntax but is a static method.Array.TrueForAllStatic Method
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls