Languages
[Edit]
EN

C# / .NET - add List into HashSet

0 points
Created by:
Mohammad-Oneal
327

In this article, we would like to show you how to add List into HashSet in C#.

Quick solution:

List<string> letters = new List<string> { "A", "B", "C" };

HashSet<string> alphabet = new HashSet<string>(letters);

 

1. Add ArrayList on HashSet creation

In this example, we add existing letters List to a new alphabet HashSet in the constructor.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> letters = new List<string> { "A", "B", "C" };

        HashSet<string> alphabet = new HashSet<string>(letters);

        foreach (string letter in alphabet)
            Console.WriteLine(letter);
    }
}

Output:

A
B
C

2. Add List to the existing HashSet

In this example, we add existing letters List to the existing alphabet HashSet using UnionWith() method.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> letters = new List<string> { "A", "B", "C" };

        HashSet<string> alphabet = new HashSet<string>();

        alphabet.UnionWith(letters);

        foreach (string letter in alphabet)
            Console.WriteLine(letter);
    }
}

Output:

A
B
C

References

  1. HashSet<T>.UnionWith(IEnumerable<T>) Method (System.Collections.Generic) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join