Start learning free

LESSON 113 OF 674 · ARRAYS I

Checking a List for a Value in C#

Lesson

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