Start learning free

LESSON 113 OF 674 · ARRAYS I

Checking a List for a Value in C# with Contains

Lesson Read the full explanation

TL ; DR:

list.Contains(x) is true when the List holds x, and false when it doesn't. Use it as the condition of an if.


List<string> colors = new List<string>(new[] {"red", "green", "blue"});

Console.WriteLine(colors.Contains("red"));    // True

Console.WriteLine(colors.Contains("pink"));   // False

if (!colors.Contains("pink")) {
    Console.WriteLine("No pink yet");
}


Full lesson:

Often you need to know if a List holds some value. Is this name on the guest list? Is this item in the cart?

Contains(x) answers that. It compares each item with x, from the first one on. It returns true as soon as one matches, or false if none does.

Put ! in front for the opposite. So !colors.Contains(x) is true when x is missing.

The answer is a bool, so it fits right into an if:

List<string> cart = new List<string>(new[] {"milk", "bread"});

if (cart.Contains("milk")) {
    Console.WriteLine("Milk is in the cart");
}

Console.WriteLine prints a bool as True or False, with a capital letter. In code, you still write true and false.

Text must match exactly. So colors.Contains("Red") is false, because the List has "red".


Your task

bag holds what is packed for a hike.

If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.

Expected output:

Water is packed
Pack a tent
STEP 1 OF 2
    Ctrl + Enter to check

    C# · ARRAYS I

    Array Membership in C#, explained

    Does the list hold this value?

    Often a program needs a yes-or-no answer: is this name on the guest list, is this item in the cart? A List<T> has a method for exactly that. Contains(x) compares each item with x, from the first one on, and returns true as soon as one is equal. If it reaches the end without a match, it returns false.

    List<string> colors = new List<string>(new[] {"red", "green", "blue"});
    Console.WriteLine(colors.Contains("red"));
    Console.WriteLine(colors.Contains("pink"));
    Console.WriteLine(colors.Contains("Red"));
    
    True
    False
    False
    

    Two details show up in that output. First, Console.WriteLine prints a bool as True or False, with a capital letter, while the literals in your code are lowercase true and false. Second, text must match exactly. "Red" is not "red", so the third check is false.

    In a file of your own, add using System; and using System.Collections.Generic; at the top.

    Using the answer in an if

    The result is a bool, so it can be the condition of an if with no comparison needed. Writing if (cart.Contains("milk") == true) works but only repeats what the method already says.

    List<string> cart = new List<string>(new[] {"milk", "bread"});
    if (cart.Contains("milk")) {
        Console.WriteLine("Milk is in the cart");
    }
    

    Put ! in front of the call for the opposite question. !cart.Contains("tea") is true when tea is missing.

    You can also keep the answer in a variable when you need it more than once:

    bool hasMap = cart.Contains("map");
    

    Here hasMap is false, because the cart holds only milk and bread. The method works for any item type that can be compared for equality, so a List<int> works the same way, with numbers in place of text. The comparison is the usual equality for that type: for strings, the characters; for numbers, the values.

    The exercise, step by step

    bag holds map, water and snacks. The task prints one line when water is packed and one when a tent is not.

    1. Check for water. The condition is bag.Contains("water"). The bag does have water, so the condition is true and Water is packed is printed.
    2. Check that the tent is missing. The condition is !bag.Contains("tent"). The call returns false, the ! turns that into true, and Pack a tent is printed.
    List<string> bag = new List<string>(new[] {"map", "water", "snacks"});
    if (bag.Contains("water")) {
        Console.WriteLine("Water is packed");
    }
    if (!bag.Contains("tent")) {
        Console.WriteLine("Pack a tent");
    }
    
    Water is packed
    Pack a tent
    

    Traps and related methods

    • Exact matching. Upper and lower case count as different, and so does a trailing space. "water " is not "water".
    • An empty list is fine: new List<int>().Contains(3) is false, since there is nothing to compare.
    • Do you need the position too? IndexOf(x) returns the index of the first match, or -1 when the value is missing. In the colors list, IndexOf("blue") is 2 and IndexOf("pink") is -1. Use Contains when only the yes-or-no answer matters, because the code then says what it means.
    • A common use. Contains is the usual guard before Add, to keep a list free of duplicates: add the item only when !list.Contains(item) is true. Where order does not matter, a HashSet<T> does this for you.
    • Speed. Contains looks at items one by one, so a long list takes longer to search. For a few items that does not matter.

    Key takeaways

    • list.Contains(x) returns a bool, so it goes straight into an if.
    • !list.Contains(x) means that x is missing.
    • Matching is exact, including case.
    • For the position of a value, use IndexOf.
    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free