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.
- Check for water. The condition is
bag.Contains("water"). The bag does have water, so the condition is true andWater is packedis printed. - Check that the tent is missing. The condition is
!bag.Contains("tent"). The call returnsfalse, the!turns that intotrue, andPack a tentis 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)isfalse, since there is nothing to compare. - Do you need the position too?
IndexOf(x)returns the index of the first match, or-1when the value is missing. In the colors list,IndexOf("blue")is 2 andIndexOf("pink")is -1. UseContainswhen only the yes-or-no answer matters, because the code then says what it means. - A common use.
Containsis the usual guard beforeAdd, to keep a list free of duplicates: add the item only when!list.Contains(item)is true. Where order does not matter, aHashSet<T>does this for you. - Speed.
Containslooks 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 abool, so it goes straight into anif.!list.Contains(x)means thatxis missing.- Matching is exact, including case.
- For the position of a value, use
IndexOf.
