HashSet contains

In this chapter you will learn:

  1. How to check if a value is in a set

Does a set contain a value

Contains method from HashSet determines whether a HashSet<T> object contains the specified element. The following code creates a set of integers and then use Contains method to check if 0 is in that set.

using System;//  java  2s.co m
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> evenNumbers = new HashSet<int>();

        for (int i = 0; i < 20; i++)
        {
            evenNumbers.Add(i);
        }


        Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);

        if (evenNumbers.Contains(0))
        {
            evenNumbers.Remove(0);
        }

        Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to create HashSet from Comparer
Home » C# Tutorial » Collections
HashSet
Set operation: Except
Set operator intersect
Remove with condition
HashSet contains
HashSet creation
HashSet removing element
Sub set operations
Hashtable
Hashtable ContainsValue
Add elements to a Hashtable
Hashtable containsKey
Remove from Hashtable
Hashtable to array
Queue
Generic Queue
Stack