LINQ / C#

LINQ All Operator

LINQ All operator is used to check whether all elements in a sequence (collection) satisfy a particular condition or not. LINQ All operator comes under Quantifier Operators category in LINQ Query Operators.

Lets take an example, we have a collection A = { 3, 6, 9, 12 } and we have to check whether all elements in this sequence is divide by 3 or not. For this we use All operator and pass predicate function condition as a parameter. 

bool isAllElementsDivisibleByThree = A.All(number => number %3 == 0)

This operator returns True if all elements satisfy condition else returns false.

Below is the syntax of All Operator

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

This is only one overload operator available which takes a predicate function. LINQ Query operator is only available in Method Syntax and not available in Query Syntax.

C# LINQ All Operator Example

In this example, we have a list of Student objects. Each student object has a property IsFeesSubmitted. In our problem scenario, we have to check that has all students submitted their fees or not?

List<Student> students = new List<Student>();

students.Add(new Student { ID = 1, Name = "Asutosh", IsFeesSubmitted = true });
students.Add(new Student { ID = 1, Name = "Kapil", IsFeesSubmitted = true });
students.Add(new Student { ID = 1, Name = "Sumit", IsFeesSubmitted = true });
students.Add(new Student { ID = 1, Name = "Rajat", IsFeesSubmitted = false });
students.Add(new Student { ID = 1, Name = "Preeti", IsFeesSubmitted = true });
students.Add(new Student { ID = 1, Name = "Kanupriya", IsFeesSubmitted = true });

//check whether all students submitted their fees or not
bool areAllStudentsSubmitTheirFees = students.All(student => student.IsFeesSubmitted == true);

Console.WriteLine(areAllStudentsSubmitTheirFees);

Result
------
False

In the above example, student Rajat has not submitted their fees yet, and his property IsFeesSubmitted value is False. Hence All operator returns false in this case.

LINQ All vs Any Operator

All and Any operator both check whether elements in a sequence satisfy a condition or not. Below are the differences between them.

All OperatorAny Operator
1. All operator is used to check whether all elements in a sequence satisfy given condition or not.1. Any operator is used to check whether any single element in a sequence satisfy a given condition or not.
2. Return True if sequence is blank.2. Return False if sequence is blank.