Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
hashset
communitycreator

How to determine if an element is present in the HashSet in C#

Surabhi Sharma

The HashSet<T> generic class in the System.Collections.Generic namespace provides the Contains() method, which is used to check if an item exists in the HashSet<T>. This method returns true if the element is present in the HashSet, and returns false otherwise.

Syntax

public bool Contains (T item);

The method takes an object of the T type as input to search in the HashSet, and returns a Boolean result.

The time complexity of this method is O(1).

Checking if element is present in HashSet using Contains() method

Example

In the example below, we create a HashSet of strings and add the names of the first six months to it with the Add() method. We then print all the elements of the HashSet with a foreach loop.

We use the Contains() method to check the presence of April. This returns true, as it is present in the HashSet.

After that, we use the Contains() method to check the presence of December. This returns false, as the HashSet does not contain December.

The Contains() method call is an O(1) operation.

using System;
using System.Collections.Generic;

class HashSetContains
{
    static void Main()
    {
        HashSet<string> monthSet = new HashSet<string>();
        monthSet.Add("January");
        monthSet.Add("February");
        monthSet.Add("March");
        monthSet.Add("April");
        monthSet.Add("May");
        monthSet.Add("June");
        Console.WriteLine("HashSet Items :");
        foreach(var elem in monthSet)
        {
            Console.WriteLine(elem);
        }
        Console.WriteLine("Does HashSet Contain 'April'? : {0}",monthSet.Contains("April"));
        Console.WriteLine("Does HashSet Contain 'December' ?: {0}",monthSet.Contains("December"));        
    }
}

RELATED TAGS

c#
hashset
communitycreator
RELATED COURSES

View all Courses

Keep Exploring