푸터 콘텐츠로 바로가기
.NET 도움말

HashSet C# (How It Works For Developers)

Programming in C# is flexible and provides a large array of data structures to effectively manage various jobs. The HashSet is one such potent data structure that offers distinct components and constant-time average complexity for fundamental operations. This post will examine the use of HashSet in C# and how it may be used with IronPDF, a powerful library for working with PDF documents.

How to use HashSet in C\

  1. Create a new Console App project.
  2. Create an object for the HashSet in C#. Add the default value to the HashSet.
  3. While adding, HashSet will automatically remove duplicate elements by checking if the element exists.
  4. Process the HashSet only unique elements one by one.
  5. Display the result and dispose of the object.

Understanding HashSet in C\

HashSet in C# is designed to provide high-performance set operations. A HashSet is the perfect collection to use in situations when you need to keep a distinct set of data since it prevents duplicate elements. It's included in the System.Collections.Generic namespace and provides quick insertion, deletion, faster retrieval, and lookup operations. In C#, use HashSet set operations methods that let you easily carry out standard set operations. The HashSet class provides set operations methods.

The following are a few C# uses for a HashSet:

Initialization and Basic Operations

Establishing a HashSet and carrying out fundamental actions such as appending, deleting, and verifying the existence of entries.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initializes a HashSet of integers
        HashSet<int> numbers = new HashSet<int>();

        // Adds elements to the HashSet
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // Removes an element from the HashSet
        numbers.Remove(2);

        // Checks for membership of an element
        bool containsThree = numbers.Contains(3);

        Console.WriteLine($"Contains 3: {containsThree}");
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initializes a HashSet of integers
        HashSet<int> numbers = new HashSet<int>();

        // Adds elements to the HashSet
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // Removes an element from the HashSet
        numbers.Remove(2);

        // Checks for membership of an element
        bool containsThree = numbers.Contains(3);

        Console.WriteLine($"Contains 3: {containsThree}");
    }
}
$vbLabelText   $csharpLabel

Initialization with Collection

Using an existing collection as the starting point for a HashSet, duplicates are immediately eliminated.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creates a list with duplicate elements
        List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 };

        // Initializes a HashSet with the list, automatically removes duplicates
        HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);

        Console.WriteLine("Unique numbers:");
        foreach (var number in uniqueNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creates a list with duplicate elements
        List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 };

        // Initializes a HashSet with the list, automatically removes duplicates
        HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);

        Console.WriteLine("Unique numbers:");
        foreach (var number in uniqueNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
$vbLabelText   $csharpLabel

Union with Another HashSet

Combining two HashSet instances to produce a new set that combines distinct items from both sets using the UnionWith function.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Merges set2 into set1
        set1.UnionWith(set2);

        Console.WriteLine("Union of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Merges set2 into set1
        set1.UnionWith(set2);

        Console.WriteLine("Union of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
$vbLabelText   $csharpLabel

Intersection with Another HashSet

Using the IntersectWith function, determine the shared components between two HashSet instances.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Keeps only elements that are present in both sets
        set1.IntersectWith(set2);

        Console.WriteLine("Intersection of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Keeps only elements that are present in both sets
        set1.IntersectWith(set2);

        Console.WriteLine("Intersection of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
$vbLabelText   $csharpLabel

Difference with Another HashSet

Using the ExceptWith function, find the elements that are in one HashSet but not in another.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Removes elements from set1 that are also in set2
        set1.ExceptWith(set2);

        Console.WriteLine("Difference of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Removes elements from set1 that are also in set2
        set1.ExceptWith(set2);

        Console.WriteLine("Difference of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
$vbLabelText   $csharpLabel

Checking for Subset or Superset:

Using the IsSubsetOf and IsSupersetOf methods, one may ascertain whether a given HashSet instance is a subset or superset of another.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 2, 3 };

        // Checks if set2 is a subset of set1
        bool isSubset = set2.IsSubsetOf(set1);

        // Checks if set1 is a superset of set2
        bool isSuperset = set1.IsSupersetOf(set2);

        Console.WriteLine($"Is set2 a subset of set1: {isSubset}");
        Console.WriteLine($"Is set1 a superset of set2: {isSuperset}");
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 2, 3 };

        // Checks if set2 is a subset of set1
        bool isSubset = set2.IsSubsetOf(set1);

        // Checks if set1 is a superset of set2
        bool isSuperset = set1.IsSupersetOf(set2);

        Console.WriteLine($"Is set2 a subset of set1: {isSubset}");
        Console.WriteLine($"Is set1 a superset of set2: {isSuperset}");
    }
}
$vbLabelText   $csharpLabel

Symmetric Difference

Using the SymmetricExceptWith technique, determine the symmetric difference (elements present in one set, but not in both).

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Keeps elements that are in set1 or set2 but not in both
        set1.SymmetricExceptWith(set2);

        Console.WriteLine("Symmetric difference of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

        // Keeps elements that are in set1 or set2 but not in both
        set1.SymmetricExceptWith(set2);

        Console.WriteLine("Symmetric difference of set1 and set2:");
        foreach (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
$vbLabelText   $csharpLabel

IronPDF

Programmers may use the C# language to produce, edit, and modify PDF documents by utilizing the IronPDF .NET library. The application offers a wide range of tools and features to enable different operations with PDF files, including creating new PDFs from HTML, converting HTML to PDF, combining or dividing PDF documents, and annotating existing PDFs with text, photos, and other data. To know more about the IronPDF, refer to the official documentation.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

Features of IronPDF

  • HTML to PDF conversion: Any kind of HTML data, including files, URLs, and HTML code strings, may be converted into PDF documents with IronPDF.
  • PDF Generation: Text, images, and other objects may be programmatically added to PDF documents using the C# programming language.
  • PDF Manipulation: IronPDF can divide a PDF file into numerous files and edit pre-existing PDF files. It can merge several PDF files into a single file.
  • PDF Forms: Because the library enables users to build and complete PDF forms, it is useful in scenarios where form data needs to be gathered and processed.
  • Security Features: IronPDF allows for PDF document encryption as well as password and permission security.

Install IronPDF

Acquire the IronPDF library; the upcoming patch requires it. To do this, enter the following code into the Package Manager:

Install-Package IronPdf

or

dotnet add package IronPdf

HashSet C# (How It Works For Developers): Figure 1 - Install IronPDF library using Package Manager Console and entering the following commands: Install-Package IronPDF or dotnet add package IronPdf.

Another option is to look for the package "IronPDF" using the NuGet Package Manager. From all the NuGet packages related to IronPDF, we may select and download the required package from this list.

HashSet C# (How It Works For Developers): Figure 2 - You can install IronPDF library using NuGet Package Manager. Search for the package ironpdf in the Browse tab, then select and install the latest version of the IronPDF.

HashSet with IronPDF

Within the C# environment, IronPDF is a powerful library that makes working with PDF documents easier. In situations where distinct data representation and effective document creation are crucial, combining the efficiency of HashSet with the document manipulation powers of IronPDF might result in creative solutions.

Benefits of Using HashSet with IronPDF

  • Data Redundancy Reduction: By ensuring that only distinct elements are kept, HashSets help to avoid data duplication. When dealing with huge datasets to remove duplicate information, this is quite helpful.
  • Effective Lookup: Basic operations such as insertion, deletion, and lookup may be performed with constant-time average complexity using HashSet. This kind of performance is very important when working with different-sized datasets.
  • Simplified Production of Documents: IronPDF streamlines the C# PDF document creation process. You may establish fast and effective processes for producing original and dynamic content for your PDFs by integrating HashSet with IronPDF.

Now let's look at a real-world scenario where using HashSet with IronPDF might be useful.

Generating PDF with Unique Data

using IronPdf;
using System;
using System.Collections.Generic;

class PdfGenerator
{
    static void Main()
    {
        // Sample user names with duplicates
        string[] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };

        // Using HashSet to ensure unique user names
        HashSet<string> uniqueUserNames = new HashSet<string>(userNames);

        // Generating PDF with unique user names
        GeneratePdf(uniqueUserNames);
    }

    static void GeneratePdf(HashSet<string> uniqueUserNames)
    {
        // Create a new PDF document using IronPDF
        HtmlToPdf renderer = new HtmlToPdf();

        // Render a PDF from an HTML document consisting of unique user names
        var pdf = renderer.RenderHtmlAsPdf(BuildHtmlDocument(uniqueUserNames));

        // Save the PDF to a file
        string pdfFilePath = "UniqueUserNames.pdf";
        pdf.SaveAs(pdfFilePath);

        // Display a message with the file path
        Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}");
    }

    static string BuildHtmlDocument(HashSet<string> uniqueUserNames)
    {
        // Build an HTML document with unique user names
        string htmlDocument = "<html><body><ul>";
        foreach (var userName in uniqueUserNames)
        {
            htmlDocument += $"<li>{userName}</li>";
        }
        htmlDocument += "</ul></body></html>";
        return htmlDocument;
    }
}
using IronPdf;
using System;
using System.Collections.Generic;

class PdfGenerator
{
    static void Main()
    {
        // Sample user names with duplicates
        string[] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };

        // Using HashSet to ensure unique user names
        HashSet<string> uniqueUserNames = new HashSet<string>(userNames);

        // Generating PDF with unique user names
        GeneratePdf(uniqueUserNames);
    }

    static void GeneratePdf(HashSet<string> uniqueUserNames)
    {
        // Create a new PDF document using IronPDF
        HtmlToPdf renderer = new HtmlToPdf();

        // Render a PDF from an HTML document consisting of unique user names
        var pdf = renderer.RenderHtmlAsPdf(BuildHtmlDocument(uniqueUserNames));

        // Save the PDF to a file
        string pdfFilePath = "UniqueUserNames.pdf";
        pdf.SaveAs(pdfFilePath);

        // Display a message with the file path
        Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}");
    }

    static string BuildHtmlDocument(HashSet<string> uniqueUserNames)
    {
        // Build an HTML document with unique user names
        string htmlDocument = "<html><body><ul>";
        foreach (var userName in uniqueUserNames)
        {
            htmlDocument += $"<li>{userName}</li>";
        }
        htmlDocument += "</ul></body></html>";
        return htmlDocument;
    }
}
$vbLabelText   $csharpLabel

In the above code example, we save unique user names retrieved from an array using a HashSet uniqueUserNames. The HashSet automatically eliminates duplicates. Next, we create an unordered list of these distinct user names in a PDF document using IronPDF. To know more about the code, check using HTML to create a PDF.

OUTPUT

HashSet C# (How It Works For Developers): Figure 3 - Output: UniqueUserNames.pdf

Conclusion

To sum up, the C# HashSet data structure is an effective tool for organizing sets of distinct items. It creates new opportunities for dynamic, one-of-a-kind, and performance-optimized PDF document creation when paired with IronPDF.

We illustrated how to use HashSet to guarantee data uniqueness while using IronPDF to create PDF documents in the example that was given. Building strong and effective C# applications may benefit from the combination of HashSet and IronPDF, whether you're working on data deduplication, reporting, or managing dynamic content. As you investigate more, take into account the many contexts in which you might utilize this combination to improve the usability and functionality of your apps.

The $799 Lite version of IronPDF comes with a permanent license, upgrade options, and a year of software support. Throughout the watermarked trial period on licensing to find out more about IronPDF's price, licensing, and free trial. Visit the Iron Software website for further information on Iron Software.

자주 묻는 질문

C#으로 PDF 문서를 생성할 때 고유한 데이터를 보장하려면 어떻게 해야 하나요?

PDF 문서를 생성하기 전에 해시세트를 사용하여 사용자 이름과 같은 고유한 데이터 요소를 저장할 수 있습니다. 이렇게 하면 중복 항목이 제거되어 더 깔끔하고 정확한 PDF 콘텐츠를 제공할 수 있습니다.

IronPDF와 함께 해시셋을 사용하면 어떤 이점이 있나요?

IronPDF와 함께 해시셋을 사용하면 PDF를 만들 때 고유 데이터를 효율적으로 관리할 수 있습니다. 해시세트는 데이터 고유성을 보장하며, IronPDF는 HTML 콘텐츠를 PDF로 변환하고 레이아웃과 스타일을 보존하는 데 탁월합니다.

C#에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 C#에서 HTML 콘텐츠를 PDF로 변환할 수 있습니다. 이 메서드를 사용하면 원래의 레이아웃과 스타일을 유지하면서 HTML 문자열을 PDF로 직접 변환할 수 있습니다.

해시셋은 C#에서 어떤 연산을 지원하나요?

c#의 HashSet는 효율적인 데이터 조작과 집합 비교를 용이하게 하는 UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith 등 다양한 집합 연산을 지원합니다.

해시셋을 PDF 문서 작성과 통합하려면 어떻게 해야 하나요?

해시세트를 PDF 문서 생성과 통합하려면 해시세트를 사용하여 데이터를 관리하고 고유성을 필터링한 후 IronPDF로 전달하여 최종 PDF 문서를 생성합니다.

동적 콘텐츠 관리에서 해시셋의 역할은 무엇인가요?

동적 콘텐츠 관리에서 해시셋은 문서 생성, 보고, 데이터 무결성 유지와 같은 작업에 필수적인 데이터를 고유하게 유지함으로써 중요한 역할을 합니다.

C# 프로젝트에 IronPDF를 어떻게 설치하나요?

다음 명령을 사용하여 NuGet 패키지 관리자를 사용하여 C# 프로젝트에 IronPDF를 설치할 수 있습니다: Install-Package IronPdf 명령을 사용하거나 .NET CLI를 사용하여 설치할 수 있습니다: 닷넷 추가 패키지 IronPdf.

해시셋이 C# 애플리케이션의 성능을 향상시킬 수 있나요?

예, 해시셋는 삽입, 삭제, 조회와 같은 기본 연산에 대한 상시 복잡성을 제공함으로써 C# 애플리케이션의 성능을 크게 향상시켜 대규모 데이터 집합을 효율적으로 관리할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.