C# | Check if a value is in LinkedList<T>

LinkedList<T>.Contains(T) method is used to check whether a value is in the LinkedList<T> or not.

Syntax:

public bool Contains (T value);

Here, value is the value to locate in the LinkedList<T>. The value can be null for reference types.



Return Value: This method returns True if value is found in the LinkedList, otherwise, False.

Below given are some examples to understand the implementation in a better way:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to check if a
// value is in LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Strings
        LinkedList<String> myList = new LinkedList<String>();
  
        // Adding nodes in LinkedList
        myList.AddLast("A");
        myList.AddLast("B");
        myList.AddLast("C");
        myList.AddLast("D");
        myList.AddLast("E");
  
        // To check if a value is in LinkedList
        Console.WriteLine(myList.Contains("B"));
    }
}

chevron_right


Output:

True

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to check if a
// value is in LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Integers
        LinkedList<int> myList = new LinkedList<int>();
  
        // Adding nodes in LinkedList
        myList.AddLast(1);
        myList.AddLast(2);
        myList.AddLast(3);
        myList.AddLast(4);
        myList.AddLast(5);
  
        // To check if a value is in LinkedList
        Console.WriteLine(myList.Contains(8));
    }
}

chevron_right


Output:

False

Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.

Reference:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.