A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.Contains(T) Method is used to check whether a HashSet object contains the specified element.
Syntax:
mySet.Contains(T item);
Here, mySet is the name of the HashSet and item is the required element to locate in the HashSet object.
Return Type: This method returns true if the HashSet object contains the specified element; otherwise, false.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< string > mySet = new HashSet< string >();
mySet.Add( "DS" );
mySet.Add( "C++" );
mySet.Add( "Java" );
mySet.Add( "JavaScript" );
if (mySet.Contains( "Java" ))
Console.WriteLine( "Required Element is present" );
else
Console.WriteLine( "Required Element is not present" );
}
}
|
Output:
Required Element is present
Example 2:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet = new HashSet< int >();
for ( int i = 0; i < 5; i++) {
mySet.Add(i * 2);
}
if (mySet.Contains(5))
Console.WriteLine( "Required Element is present" );
else
Console.WriteLine( "Required Element is not present" );
}
}
|
Output:
Required Element is not present
Reference: