What is List.Contains() method in C#?
The List<T> class in C# is a list of objects having a specific type T. This class is a basic component of the .NET framework’s generic collection types and provides flexibility and convenience for managing collections of objects. We’ll learn about a very useful method of List<T> class, List.Contains(), which helps in the search functionality of many real-world applications.
The List.Contains() method
It contains a method List.Contains() to check the existence of specific elements within lists. It helps us to check the presence or absence of a particular element in the list. We’ll go through the details of List.Contains() method and some code examples.
Syntax
It accepts a single parameter of the same type as the elements in the list and returns a boolean value.
public bool Contains (T item)
Here’s a breakdown of the syntax:
Access modifier:
publicindicates that the method is accessible from outside the class.Return type:
boolspecifies that the method returns a boolean value. It returnstrueif the element is found andfalseif it is not in the list.Parameter:
T itemrepresents the item of typeTto be searched in the list.
Example: Checking book availability
Let’s understand the usage of List.Contains() method with the help of a basic code example. We’ll use this method to check if a student exists in a class list through the student’s name.
using System;using System.Collections.Generic;class Program{static void Main(){// Creating a list of student namesList<string> studentNames = new List<string> { "Alice", "Bob", "Charlie", "David", "Emma" };// Student name to search forstring studentToFind1 = "Bob";string studentToFind2 = "Alexa";// Checking if the list contains the specified student “studentToFind1”if (studentNames.Contains(studentToFind1)){Console.WriteLine($"The list contains the student: {studentToFind1}.");}else{Console.WriteLine($"The list does not contain the student: {studentToFind1}");}// Checking if the list contains the specified student “studentToFind2”if (studentNames.Contains(studentToFind2)){Console.WriteLine($"The list contains the student: {studentToFind2}.");}else{Console.WriteLine($"The list does not contain the student: {studentToFind2}");}}}
Code explanation
Here is the explanation of the above code example:
Line 9: We create a list of type
stringnamed asstudentNamesand populate the list with a few names of the students.Lines 12–13: We create two string variables,
studentToFind1andstudentToFind2, to store the student’s name we want to search in the list.Lines 16–23: In the
if elseblock, we use theContains()method of theList<T>class to check if thestudentNameslist contains the studentstudentToFind1and print the message on the console.Lines 26–33: In the
if elseblock, we use theContains()method of theList<T>class to check if thestudentNameslist contains the studentstudentToFind2and print the message on the console.
Let’s look at another example of List.Contains() method usage.
Example: Book existence verification
We’ll use this method to check whether a book exists in the library or not using the book and author’s name.
using System;using System.Collections.Generic;class Program{static void Main(string[] args){// Creating a list of book namesList<Book> library = new List<Book>();library.Add(new Book("1984", "George Orwell"));library.Add(new Book("To Kill a Mockingbird", "Harper Lee"));library.Add(new Book("The Great Gatsby", "F. Scott Fitzgerald"));// Checking if the book exists in the library or notif (library.Contains(new Book("To Kill a Mockingbird", "Harper Lee"))) {Console.WriteLine("Already Exists");}else {Console.WriteLine("Doesn't Exit");}}}public class Book : IEquatable<Book>{public Book(string title, string author){this.Title = title;this.Author = author;}public string Title { get; set; }public string Author { get; set; }public bool Equals(Book book){// Checking the equality on the basis of title and authorif (book == null) return false;return this.Title == book.Title && this.Author == book.Author;}}
Code explanation
Here is the explanation of the above code example:
Lines 9–13: We create a list of type
Booknamed asLibraryand populate the list with a few names of the books and authors.Lines 15–20: In the
if elseblock, we use theContains()method of theList<T>class to check if theLibrarylist contains the book and print the message on the console.Lines 24–42: The
Bookclass has two properties to represent a book: title and author. It implements theIEquatable<Book>interface for equality check. It overrides theIEquatable<T>.Equalsmethod and checks the equality of books based on title and author. It helps us to use theContainsmethod by just passing the title and author of the book.
Conclusion
The List.Contains() method efficiently checks the presence or absence of an element in the list using a very simple and straightforward approach. It also ensures code safety by verifying the presence of elements before accessing or manipulating them. This makes it an indispensable tool for developers working with collections in various applications.
Free Resources