C# HashSet UnionWith

Description

HashSet UnionWith modifies the current HashSet object to contain all elements that are present in itself, the specified collection, or both.

Syntax

HashSet.UnionWith has the following syntax.


public void UnionWith(
  IEnumerable<T> other
)

Parameters

HashSet.UnionWith has the following parameters.

  • other - The collection to compare to the current HashSet object.

Example

The following example demonstrates how to merge two disparate sets.


/*from   w  w w .  ja v  a  2 s  . co  m*/
using System;
using System.Collections.Generic;

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

        for (int i = 0; i < 5; i++)
        {
            evenNumbers.Add(i * 2);
            oddNumbers.Add((i * 2) + 1);
        }
        HashSet<int> numbers = new HashSet<int>(evenNumbers);
        numbers.UnionWith(oddNumbers);

        foreach (int i in numbers)
        {
            Console.WriteLine(i);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections.Generic »




HashSet
LinkedList
LinkedListNode
List
Queue
SortedSet
Stack