Linq All Operator in C#

LINQ (Language Integrated Query) is a powerful feature in C# that allows you to query data from different sources such as arrays, lists, databases, and XML documents. One of the most commonly used LINQ operators is All, which allows you to check if all elements in a collection match a specific condition. In this lesson, we will learn how to use All in C#.

Let’s assume we have a collection of integers, and we want to check if all of the elements in the collection are even numbers. To achieve this, we can use the All operator.

Here’s the code to achieve this:
var numbers = new List<int> { 2, 4, 6, 8 };

if (numbers.All(number => number % 2 == 0))
{
    Console.WriteLine("All numbers are even.");
}
else
{
    Console.WriteLine("Not all numbers are even.");
}

In the above code, we first create a list of integers. We then use the All method along with a lambda expression to check if all elements in the collection are even. The lambda expression takes each element in the collection and checks if it’s divisible by 2. If all elements are divisible by 2, the All method returns true, otherwise, it returns false.

We then use an if statement to check the result of the All method. If it returns true, we print the message “All numbers are even.” Otherwise, we print the message “Not all numbers are even.”

The output of the above code would be:

All numbers are even.

As we can see, the All operator has determined that all elements in the collection are even, and we have printed the appropriate message.

In conclusion, LINQ All in C# is a powerful feature that allows you to check if all elements in a collection match a specific condition. By using this feature, you can easily determine if your data meets certain criteria and take appropriate action based on the result.