ANY is used to see if something is true or false in a list.

In other words, ANY is used to find if a bool condition is satisfied on any item in a collection.

For example, you might want to find if a dog exists that is of the age of 4. Or if a dog exists that is older than 20 years. 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 dogExistsWithAgeFour = dogList.Any(d => d.Age == 4);

        Console.WriteLine($"A dog exists with an age of 4: {dogExistsWithAgeFour}");

        // Prints: 
        // A dog exists with an age of 4: True

        bool dogExistsWithAgeOverTwenty = dogList.Any(d => d.Age > 20);

        Console.WriteLine($"A dog exists with an age over 20: {dogExistsWithAgeOverTwenty}");

        // Prints: 
        // A dog exists with an age over 20: False
    }
}

Here we used an int, Age, to check a bool condition on the age of the dog.

We can use OwnerName to check if there’s an owner called Bob.

bool bobExists = dogList.Any(d => d.OwnerName == "Bob");

Console.WriteLine($"An owner exists that's called Bob: {bobExists}");

// Prints: 
// An owner exists that's called Bob: False

You can also combine conditions.

We can combine OwnerName and Age to find if Michael has a dog that is older than 12 years.

bool michaelHasAnOldDog = dogList.Any(d => d.Age > 12 && d.OwnerName == "Michael");

Console.WriteLine($"Michael has an old dog: {michaelHasAnOldDog}");

// Prints: 
// Michael has an old dog: True

What is the difference between ANY and CONTAINS?

ANY and CONTAINS has the same result, ie they find if something exists in a collection. But the execution time varies somewhat. This depends on the underlying type of collection. For example, a HashSet can find your result extremely fast using CONTAINS, while ANY becomes much slower at very big collections as it has to go through all the items and check each individually.

In other words, if using a HashSet, then CONTAINS becomes O(1) complexity. If you use ANY on this underlying type the complexity becomes O(n).

So why use ANY? With ANY you can pass a function pointer (delegate) to the ANY function which can do more advanced pattern matching. CONTAINS can only be used to see if an exact object exists within the collection.

Also, CONTAINS works much easier on simple collections, like a list with only strings or integers. It becomes more cumbersome to find the exact object using CONTAINS if the object is a complex type, like the class Dog, since you must pass the actual reference to the item itself. It does not work to copy all the parameters of the item and check for it.

So the bottom line is that ANY is more flexible and CONTAINS trades flexibility for speed.

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

    var maxDog = new Dog() { Name = "Max", Age = 4, OwnerName = "Michael" };

    dogList.Add(maxDog);

    // True
    bool anyResult = dogList.Any(DogIsNamedMax);

    // True
    bool containsResultUsingReference = dogList.Contains(maxDog);

    // False
    bool containsResultUsingNewClass = dogList.Contains(new Dog() { Name = "Max", Age = 4, OwnerName = "Michael" });
}

public static bool DogIsNamedMax(Dog dog)
{
    if (dog.Name == "Max")
        return true;

    return false;
}

More on CONTAINS:

More on Big O (Ordo Complexity):

More on Delegates:

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?