This is a C# extension method. It tells us if all the elements in a collection match a certain condition. It returns true or false.
System.Linq
All()
is part of the System.Linq
namespace in .NET. We often want to call All()
on the result of a query expression using other LINQ features.
To begin, include the System.Linq
namespace. Next, pass in a lambda expression to the All method. We pass 1 argument to the All()
method, usually a lambda expression.
bool
(whether it matches the condition).All()
on the integer array with 3 different lambdas. The All()
method returns true, false and then true again.using System; using System.Linq; 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);True False True
List
, query exampleWe can use All()
on a query expression to create more complex meanings. Here we use All()
on a List
generic type.
List
that have lengths of exactly 4 characters.All()
method returns true because all 4-letter strings are uppercase strings.using System; using System.Linq; using System.Collections.Generic; var colors = new List<string>() { "BLUE", "GREY", "white" }; // True if all strings of length 4 are in uppercase. var result = (from color in colors where color.Length == 4 select color).All(element => element == element.ToUpper()); Console.WriteLine("RESULT: {0}", result);RESULT: True
Why would we use All()
instead of looping over elements and using an if
-statement? The All method is more compact. And it can be part of a more complex LINQ statement.
All()
is probably slower due to the requirement that a Func
instance be created.As part of the LINQ extensions, All()
serves a specific purpose. For arrays, we can also use the Array.TrueForAll
method, which uses the same syntax but is a static
method.