Hashset.Exceptwith(Ienumerable) Method In C#

In this article, we will discuss the HashSet<T>.ExceptWith(IEnumerable<T>) method in C# with their syntax and examples.

What is the HashSet<T>.ExceptWith(IEnumerable<T>) Method?

The ExceptWith method is widely used to modify the HashSet<T> object by removing all elements in the other collection. This method is the equivalent of the mathematical set subtraction. The time complexity of this method is big O(n) , where n is the total number of elements present in the other specified collection. This method will take the same elements in both sets and assign the resultant to the original set.

For example, there are two HashSets that are of the same type. Let us say both are integer datatypes. The first hashset is HashSet1 , and the other hashset is HashSet2 . After that, we use the ExceptWith method on HashSet1 by giving the HashSet2 as the other parameter. The elements in both the hashsets are removed from the HashSet1.

Syntax:

It has the following syntax:

Example

public void ExceptWith(IEnumerable<T> other);

Here, the other parameter will represent the collection whose elements will be removed from the current HashSet<T> . This method is a void function, so it will return nothing, but it changes the current HashSet object. It is the most efficient method for performing a set difference operation.

Example:

Let us take a program to demonstrate the working of the ExceptWith method with hashsets in C#.

Example

using System;

using System.Collections.Generic;

namespace Example

{

    class Program

    {

        static void Main(string[] args)

        {

            // first HashSet with some initial items

            HashSet<string> hashSet1 = new HashSet<string> { "Apple", "Banana", "Milk", "Bread" };

            // second HashSet with some initial items

            HashSet<string> hashSet2 = new HashSet<string> { "Milk", "Bread", "Chips" };

            // removing the items of second hashset from the first hashset

            hashSet1.ExceptWith(hashSet2);

            // Display the updated first hashset

            Console.WriteLine("Items in the hashSet1 after removing items from hashSet2:");

            foreach (string item in hashSet1)

            {

                Console.WriteLine(item);

            }

        }

    }

}

Output:

Explanation:

This program illustrates the ExceptWith method when used with the hashsets. In this example, two hashsets are initialized with some elements, which are named as hashSet1 and hashSet2 . After that, the ExceptWith method is called on hashSet1 with hashSet2 passes as an argument. This method removed the common elements in both the hashsets from the hashSet1. After that, a foreach loop is used to print the updated hashSet1.

Example 2:

Let us take a C# program to demonstrate the ExceptWith method used in small real-life incident.

Example

using System;

using System.Collections.Generic;

namespace HashSetExample

{

    class Program

    {

        static void Main(string[] args)

        {

            // Suppose we have a list of students who attended a science fair

            HashSet<string> allStudents = new HashSet<string>

            {

                "Ramu", "Laxman", "sita", "urmila", "ravan", "Sophia", "Michael"

            };

            // Now, let's say we have a list of students who won prizes at the science fair

            HashSet<string> prizeWinners = new HashSet<string>

            {

                "Ramu", "sita", "Sophia"

            };

            Console.WriteLine("List of all students who attended the science fair:");

            foreach (string student in allStudents)

            {

                Console.WriteLine(student);

            }

            Console.WriteLine("\nList of students who won prizes at the science fair:");

            foreach (string winner in prizeWinners)

            {

                Console.WriteLine(winner);

            }

            // Now, let's find out who attended the science fair but didn't win any prize

            allStudents.ExceptWith(prizeWinners);

            Console.WriteLine("\nList of students who attended the science fair but didn't win any prize:");

            foreach (string attendee in allStudents)

            {

                Console.WriteLine(attendee);

            }

        }

    }

}

Output:

Explanation:

In this example, we use a simple daily life example where an ExceptWith method is used. This program contains allStudents and prizeWinners hashsets. The allStudents hashset contains the names of all students who attended a science fair. The prixeWinners hashset contains the names of the students who won a science fair. If the problem is to get the students who attended the science fair and did not win any prizes, we can use the ExceptWtih method. It will give the students who attended the science fair and not win prizes.

Example 3:

Let us take another C# program where the List is taken as another parameter to ExceptWith method.

Example

using System;

using System.Collections.Generic;

class Program

{

    static void Main(string[] args)

    {

        HashSet<string> shoppingCart = new HashSet<string> { "Apple", "Banana", "Milk", "Bread" };

        // List representing items to be removed from the shopping cart

        List<string> itemsToRemove = new List<string> { "Milk", "Bread", "Chips" };

        shoppingCart.ExceptWith(itemsToRemove);

        // Display the updated shopping cart

        Console.WriteLine("Items in the shopping cart after removing unwanted items:");

        foreach (string item in shoppingCart)

        {

            Console.WriteLine(item);

        }

    }

}

Output:

Explanation:

In this program, the first shoppingCart is initialized to represent a shopping cart, and then a list is initialized to represent the items that should be removed from the present shopping cart. As usually ExceptWith method is used to remove the common elements. After that, a loop is used to display the items in updated shopping cart.

Input Required

This code uses input(). Please provide values below: