CONTAINS is used to see if something exists within a list.

In other words, CONTAINS is used to check if any elements in a collection satisifies a specified value.

For example, you might want to see if a dog with a specific name exists.

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

    dogNames.Add("Max");
    dogNames.Add("Rocky");
    dogNames.Add("Mortimer");
    dogNames.Add("Toby");
    dogNames.Add("Cooper");

    bool result = dogNames.Contains("Max");

    Console.WriteLine($"A dog exists that is called Max: {result}");

    // Prints:
    // A dog exists that is called Max: 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 ANY:

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?