C# | Check if an element is in the Collection<T>

Collection<T>.Contains(T) method is used to determine whether an element is in the Collection<T>.

Syntax:

public bool Contains (T item);

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

Return Value: This method return True if item is found in the Collection<T>, 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 an
// element is in the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of strings
        Collection<string> myColl = new Collection<string>();
  
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
  
        // Checking if an element is in the Collection
        // The function returns "True" if the
        // item is present in Collection
        // else returns "False"
        Console.WriteLine(myColl.Contains("A"));
    }
}

chevron_right


Output:

True

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to check if an
// element is in the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of ints
        Collection<int> myColl = new Collection<int>();
  
        myColl.Add(2);
        myColl.Add(3);
        myColl.Add(4);
        myColl.Add(5);
  
        // Checking if an element is in the Collection
        // The function returns "True" if the
        // item is present in Collection
        // else returns "False"
        Console.WriteLine(myColl.Contains(6));
    }
}

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.