ALL is used to see if everything is true or false in a list.

In other words, ALL is used to check if all elements in a collection satisfies a specified condition.

For example, you might want to see if all dogs in a list is over 2 years old. To accomplish this, we use so-called Lambda Expressions which comprises the LINQ language.

class Program
{
    public class Dog
    {
        public string Name { get; set; }

        public int Age { get; set; }

        public string OwnerName { get; set; }
    }

    static void Main(string[] args)
    {
        List<Dog> dogList = new List<Dog>();

        dogList.Add(new Dog() { Name = "Max", Age = 4, OwnerName = "Michael" });
        dogList.Add(new Dog() { Name = "Rocky", Age = 10, OwnerName = "Michael" });
        dogList.Add(new Dog() { Name = "Mortimer", Age = 14, OwnerName = "Michael" });
        dogList.Add(new Dog() { Name = "Toby", Age = 5, OwnerName = "May" });
        dogList.Add(new Dog() { Name = "Cooper", Age = 11, OwnerName = "May" });

        bool result = dogList.All(d => d.Age > 2);

        Console.WriteLine($"All dogs are over 2 years old: {result}");

        // Prints:
        // All dogs are over 2 years old: True
    }
}

Here we used an int, Age, to check a bool condition on all the ages of the dogs.

We can use the string OwnerName to check if all the owners are called Michael.

bool result = dogList.All(d => d.OwnerName == "Michael");

Console.WriteLine($"All dogs have an owner called Michael {result}");

// Prints:
// All dogs have an owner called Michael: False

You can also combine conditions.

We can combine OwnerName and Age to find if all the dogs are younger than 30 years and has an owner who’s name starts with M.

bool result = dogList.All(d => d.Age < 30 && d.OwnerName.StartsWith('M'));

Console.WriteLine($"All dogs are younger than 30 and has an owner with the first letter M: {result}");

// Prints:
// All dogs are younger than 30 and has an owner with the first letter M: True
Twitter
YouTube
Facebook
LinkedIn
Instagram
RSS

Popular articles


Business Bro 7 YouTube

Check out my YouTube Channel - tips for increasing your salary, work satisfaction and knowledge. I will help you achieve your goals. You can do anything if you put your mind to it!

🎥 Link: BusinessBro7 - Youtube Channel

Startups vs Big Tech Company - The best Work Place for Junior and Senior programmers?