CSharp - Set Union Intersect Except

Introduction

UnionWith adds all the elements in the second set to the original set excluding duplicates.

IntersectWith removes the elements that are not in both sets.

We can extract all the vowels from our set of characters as follows:

Demo

using System;
using System.Collections.Generic;
class MainClass/*w  w w .j  a v  a 2  s . c  om*/
{
   public static void Main(string[] args)
   {
     var letters = new HashSet<char> ("this is a test fox ");
     letters.IntersectWith ("aeiou");
     foreach (char c in letters) 
         Console.Write (c);     
   }
}

Result

ExceptWith removes the specified elements from the source set.

Here, we strip all vowels from the set:

Demo

using System;
using System.Collections.Generic;
class MainClass//from  w  w w.  jav  a 2  s.  c o m
{
   public static void Main(string[] args)
   {

      var letters = new HashSet<char> ("this is a test ok");
      letters.ExceptWith ("aeiou");
      foreach (char c in letters)
         Console.Write (c);
   }
}

Result

SymmetricExceptWith removes all but the elements that are unique to one set or the other:

Demo

using System;
using System.Collections.Generic;
class MainClass// w ww  .  j a va 2 s  .c  o  m
{
   public static void Main(string[] args)
   {

     var letters = new HashSet<char> ("the quick brown fox");
     letters.SymmetricExceptWith ("the lazy brown fox");

     foreach (char c in letters) Console.Write (c);
   }
}

Result