List Contains Method
This page was last reviewed on Oct 27, 2023.
Dot Net Perls
Contains. This C# method scans a List. It searches for a specific element to see if that element occurs at least once in the collection.
List Find, Exists
Shows a list
Contains is a useful method that declaratively searches. To use Contains, no for-loop is required. You can type (and maintain) less code.
String Contains
Contains example. We add System.Collections.Generic at the top. The example in the program shows the Contains extension being used on the List type with a case-insensitive search.
Part 1 A string List is constructed. The code adds 3 string literals to the collection's internal array through the Add method.
String Literal
List Add
Part 2 We try to find the element "dog," and we use the default comparison logic, which means it is case-sensitive.
Part 3 We call Contains with StringComparer.OrdinalIgnoreCase, which implements IEqualityComparer. This is an insensitive string search.
Part 4 Contains returns a bool. When an element is not found, Contains returns false. We can store the result in an expression.
Shows a list
using System; using System.Collections.Generic; using System.Linq; // Part 1: create List with three elements. var list = new List<string>(); list.Add("cat"); list.Add("dog"); list.Add("moth"); // Part 2: search for this element. if (list.Contains("dog")) { Console.WriteLine("dog was found"); } // Part 3: search for this element in any string case. // ... This is the LINQ method with the same name. if (list.Contains("MOTH", StringComparer.OrdinalIgnoreCase)) { Console.WriteLine("MOTH was found (insensitive)"); } // Part 4: this element is not found. Console.WriteLine(list.Contains("fish"));
dog was found MOTH was found (insensitive) False
Benchmark. We benchmark the performance of List Contains and a custom for-loop on a small List. Only a few elements are searched by each method.
Version 1 This version of the code uses a for-loop to test each element in the List, exiting early if a match is found.
Version 2 This version uses the Contains method on the List, which reduces the amount of code needed.
Result A custom for-loop was faster. Typically writing a for-loop that does a search is faster than using a built-in method.
using System; using System.Collections.Generic; using System.Diagnostics; class Program { /// <summary> /// Custom implementation. /// </summary> static bool ContainsLoop(List<string> list, string value) { for (int i = 0; i < list.Count; i++) { if (list[i] == value) { return true; } } return false; } const int _max = 100000000; static void Main() { var list = new List<string>(); list.Add("one"); list.Add("two"); list.Add("three"); list.Add("four"); list.Add("five"); var s1 = Stopwatch.StartNew(); // Version 1: use loop to search a list. for (int i = 0; i < _max; i++) { bool f = ContainsLoop(list, "four"); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use Contains method. for (int i = 0; i < _max; i++) { bool f = list.Contains("four"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }
19.22 ns For-loop, string comparisons [ContainsLoop] 54.60 ns Contains method [Contains]
Discussion. System.Linq is included by default in new Console applications in Visual Studio. It will allow you to call a separate Contains generic method on all IEnumerable types.
Warning LINQ extension methods are often slower. They operate on the IEnumerable interface.
Detail The LINQ Contains method accepts 2 parameters (it accepts an IEqualityComparer).
Internals. Contains performs a linear search through the elements, starting with the first element, and uses Equals to check each element value.
Info This is often much slower than a Dictionary. The LINQ method also does a linear search.
A summary. We used the Contains method on List. We saw how this method differs from the LINQ Contains method. The methods are implemented with a forward linear search.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 27, 2023 (edit link).
© 2007-2024 Sam Allen.