How to determine if a value exists in a linked list in C#

The LinkedList<T> generic class in the System.Collections.Generic namespace provides the Contains() method, which can be used to determine if a specified value exists in a linked list in C#.

Syntax

public bool Contains (T value);
  • It takes the T value as input, to be searched in the linked list.

  • It returns true if the value is present in the linked list and false otherwise.

Things to note

  • This method is an O(n) operation, as it performs a linear search in the linked list and may have to traverse all the elements in the worst case.

  • The input value passed can be null for reference types.

Determining if a value is present in linked list using Contains() method

Code example

In the code below, we created a linked list of strings and added the names of few months to it. The linked list contains four strings: January, February, March, and April.

We also created a helper method, Print(), to display the linked list nodes.

Now, we call the Contains() method by passing the March string to find it in the list, and it performs a linear search in the list and returns true. This is shown in the output as well.

Next, we call the Contains() method by passing the input string as December to find in the list, and it returns false, as December does not exist in the linked list.

Please note that the LinkedList<T> class is maintained internally as a doubly-linked list and Contains() is an O(n) operation.

The program prints the below output and exits.

LinkedList Elements
January, February, March, April, 

Does node with value March exists in linked list ? True
Does node with value December exists in linked list ? False
using System;
using System.Collections.Generic;
class LinkedListContains
{
static void Main()
{
LinkedList<string> monthList = new LinkedList<string>();
monthList.AddLast("January");
monthList.AddLast("February");
monthList.AddLast("March");
monthList.AddLast("April");
Console.WriteLine("LinkedList Elements");
Print(monthList);
string searchMonth1 = "March", searchMonth2="December";
bool result = monthList.Contains(searchMonth1);
Console.WriteLine($"Does node with value {searchMonth1} exist in linked list? {result}");
result = monthList.Contains(searchMonth2);
Console.WriteLine($"Does node with value {searchMonth2} exist in linked list? {result}");
}
private static void Print(LinkedList<string> list)
{
foreach (var node in list)
{
Console.Write(node + ", ");
}
Console.WriteLine("\n");
}
}

Free Resources