Przejdź do treści stopki
POMOC .NET

HashSet C# (jak to działa dla programistów)

Programowanie w języku C# jest elastyczne i zapewnia szeroki wachlarz struktur danych, umożliwiających efektywne zarządzanie różnymi zadaniami. HashSet jest jedną z takich potężnych struktur danych, która oferuje odrębne komponenty i stałą średnią złożoność czasową dla podstawowych operacji. W tym poście przyjrzymy się wykorzystaniu HashSet w języku C# oraz temu, jak można go używać z IronPDF, potężną biblioteką do pracy z dokumentami PDF.

Jak używać HashSet w C

  1. Utwórz nowy projekt aplikacji konsolowej.
  2. Utwórz obiekt dla HashSet w języku C#. Dodaj wartość domyślną do HashSet.
  3. Podczas dodawania HashSet automatycznie usunie zduplikowane elementy, sprawdzając, czy dany element już istnieje.
  4. Przetwarzaj unikalne elementy z HashSetu pojedynczo.
  5. Wyświetl wynik i zwolnij obiekt.

Zrozumienie HashSet w C

HashSet w języku C# został zaprojektowany w celu zapewnienia wysokowydajnych operacji na zbiorach. HashSet to idealna kolekcja do wykorzystania w sytuacjach, gdy trzeba zachować odrębny zestaw danych, ponieważ zapobiega ona powielaniu elementów. Znajduje się w przestrzeni nazw System.Collections.Generic i zapewnia szybkie wstawianie, usuwanie, szybsze pobieranie oraz operacje wyszukiwania. W języku C# należy używać metod operacji na zbiorach z klasy HashSet, które pozwalają w łatwy sposób wykonywać standardowe operacje na zbiorach. Klasa HashSet udostępnia metody operacji na zbiorach.

Poniżej przedstawiono kilka zastosowań HashSet w języku C#:

Inicjalizacja i podstawowe operacje

Tworzenie zestawu HashSet i wykonywanie podstawowych czynności, takich jak dodawanie, usuwanie i sprawdzanie istnienia wpisów.

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}");
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		' Initializes a HashSet of integers
		Dim numbers As New HashSet(Of Integer)()

		' 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
		Dim containsThree As Boolean = numbers.Contains(3)

		Console.WriteLine($"Contains 3: {containsThree}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Inicjalizacja za pomocą kolekcji

Wykorzystanie istniejącej kolekcji jako punktu wyjścia dla HashSet pozwala natychmiast wyeliminować duplikaty.

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);
        }
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		' Creates a list with duplicate elements
		Dim duplicateNumbers As New List(Of Integer) From {1, 2, 2, 3, 3, 4}

		' Initializes a HashSet with the list, automatically removes duplicates
		Dim uniqueNumbers As New HashSet(Of Integer)(duplicateNumbers)

		Console.WriteLine("Unique numbers:")
		For Each number In uniqueNumbers
			Console.WriteLine(number)
		Next number
	End Sub
End Class
$vbLabelText   $csharpLabel

Połączenie z innym zestawem HashSet

Połączenie dwóch instancji HashSet w celu utworzenia nowego zestawu, który łączy różne elementy z obu zestawów przy użyciu funkcji UnionWith.

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);
        }
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
		Dim set2 As New HashSet(Of Integer) From {3, 4, 5}

		' Merges set2 into set1
		set1.UnionWith(set2)

		Console.WriteLine("Union of set1 and set2:")
		For Each item In set1
			Console.WriteLine(item)
		Next item
	End Sub
End Class
$vbLabelText   $csharpLabel

Przecinanie się z innym zestawem HashSet

Za pomocą funkcji IntersectWith określ wspólne elementy między dwiema instancjami HashSet.

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);
        }
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
		Dim set2 As New HashSet(Of Integer) From {3, 4, 5}

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

		Console.WriteLine("Intersection of set1 and set2:")
		For Each item In set1
			Console.WriteLine(item)
		Next item
	End Sub
End Class
$vbLabelText   $csharpLabel

Różnica w stosunku do innego zestawu HashSet

Za pomocą funkcji ExceptWith znajdź elementy, które znajdują się w jednym zestawie HashSet, ale nie w innym.

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);
        }
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
		Dim set2 As New HashSet(Of Integer) From {3, 4, 5}

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

		Console.WriteLine("Difference of set1 and set2:")
		For Each item In set1
			Console.WriteLine(item)
		Next item
	End Sub
End Class
$vbLabelText   $csharpLabel

Sprawdzanie podzbioru lub nadzbioru:

Korzystając z metod IsSubsetOf i IsSupersetOf, można ustalić, czy dana instancja HashSet jest podzbiorem lub nadzbiorem innej.

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}");
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
		Dim set2 As New HashSet(Of Integer) From {2, 3}

		' Checks if set2 is a subset of set1
		Dim isSubset As Boolean = set2.IsSubsetOf(set1)

		' Checks if set1 is a superset of set2
		Dim isSuperset As Boolean = set1.IsSupersetOf(set2)

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

Różnica symetryczna

Wykorzystując technikę SymmetricExceptWith, określ różnicę symetryczną (elementy obecne w jednym zbiorze, ale nie w obu).

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 lub 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 lub set2 but not in both
        set1.SymmetricExceptWith(set2);

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

Module Program
    Sub Main()
        Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
        Dim set2 As New HashSet(Of Integer) From {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:")
        For Each item In set1
            Console.WriteLine(item)
        Next
    End Sub
End Module
$vbLabelText   $csharpLabel

IronPDF

Programiści mogą używać języka C# do tworzenia, edytowania i modyfikowania dokumentów PDF, klubzystając z biblioteki IronPDF .NET. Aplikacja oferuje szeroki zakres narzędzi i funkcji umożliwiających różne operacje na plikach PDF, w tym tworzenie nowych plików PDF z HTML, konwersję HTML do PDF, łączenie lub dzielenie dokumentów PDF oraz dodawanie adnotacji do istniejących plików PDF w postaci tekstu, zdjęć i innych danych. Aby dowiedzieć się więcej o IronPDF, zapoznaj się z oficjalną dokumentacją.

IronPDF wyróżnia się w konwersji HTML do PDF, zapewniając precyzyjne zachowanie oryginalnych układów i stylów. Idealnie nadaje się do tworzenia plików PDF z treści internetowych, takich jak raporty, faktury i dokumentacja. Dzięki obsłudze plików HTML, adresów URL i surowych ciągów znaków HTML, IronPDF z łatwością tworzy wysokiej jakości dokumenty 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");
    }
}
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");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

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

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

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Funkcje IronPDF

  • Konwersja HTML do PDF: Za pomocą IronPDF można konwertować dowolne dane HTML, w tym pliki, adresy URL i ciągi kodu HTML, na dokumenty PDF.
  • Generowanie plików PDF: Tekst, obrazy i inne obiekty można programowo dodawać do dokumentów PDF przy użyciu języka programowania C#.
  • Manipulacja plikami PDF: IronPDF może dzielić plik PDF na wiele plików oraz edytować istniejące pliki PDF. Może łączyć kilka plików PDF w jeden plik.
  • Formularze PDF: Ponieważ biblioteka umożliwia użytkownikom tworzenie i wypełnianie formularzy PDF, jest przydatna w sytuacjach, w których konieczne jest gromadzenie i przetwarzanie danych z formularzy.
  • Funkcje bezpieczeństwa: IronPDF umożliwia szyfrowanie dokumentów PDF, a także zabezpieczenia hasłem i uprawnieniami.

Zainstaluj IronPDF

Pobierz bibliotekę IronPDF; wymaga tego nadchodząca aktualizacja. Aby to zrobić, wprowadź następujący kod do menedżera pakietów:

Install-Package IronPdf

lub

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 lub dotnet add package IronPdf.

Inną opcją jest wyszukanie pakietu "IronPDF" za pomocą menedżera pakietów NuGet. Spośród wszystkich pakietów NuGet związanych z IronPDF możemy wybrać i pobrać wymagany pakiet z tej listy.

HashSet C# (Jak to działa dla programistów): Rysunek 2 – Bibliotekę IronPDF można zainstalować za pomocą menedżera pakietów NuGet. Wyszukaj pakiet ironpdf w zakładce Przeglądaj, a następnie wybierz i zainstaluj najnowszą wersję IronPDF.

HashSet z IronPDF

W środowisku C# IronPDF to potężna biblioteka, która ułatwia pracę z dokumentami PDF. W sytuacjach, w których kluczowe znaczenie ma wyraźna reprezentacja danych i efektywne tworzenie dokumentów, połączenie wydajności HashSet z możliwościami manipulacji dokumentami oferowanymi przez IronPDF może zaowocować kreatywnymi rozwiązaniami.

Korzyści z używania HashSet z IronPDF

  • Ograniczenie nadmiarowości danych: Dzięki temu, że zachowywane są tylko unikalne elementy, zestawy HashSet pomagają uniknąć powielania danych. Jest to bardzo pomocne podczas pracy z ogromnymi zbiorami danych w celu usunięcia zduplikowanych informacji.
  • Efektywne wyszukiwanie: Podstawowe operacje, takie jak wstawianie, usuwanie i wyszukiwanie, mogą być wykonywane ze stałą średnią złożonością czasową przy użyciu HashSet. Tego rodzaju wydajność jest bardzo ważna podczas pracy z zestawami danych o różnej wielkości.
  • Uproszczone tworzenie dokumentów: IronPDF usprawnia proces tworzenia dokumentów PDF w języku C#. Możesz stworzyć szybkie i skuteczne procesy tworzenia oryginalnych i dynamicznych treści do plików PDF, integrując HashSet z IronPDF.

Przyjrzyjmy się teraz rzeczywistemu scenariuszowi, w którym użycie HashSet z IronPDF może być przydatne.

Generowanie plików PDF z unikalnymi danymi

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;
    }
}
Imports IronPdf
Imports System
Imports System.Collections.Generic

Friend Class PdfGenerator
	Shared Sub Main()
		' Sample user names with duplicates
		Dim userNames() As String = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" }

		' Using HashSet to ensure unique user names
		Dim uniqueUserNames As New HashSet(Of String)(userNames)

		' Generating PDF with unique user names
		GeneratePdf(uniqueUserNames)
	End Sub

	Private Shared Sub GeneratePdf(ByVal uniqueUserNames As HashSet(Of String))
		' Create a new PDF document using IronPDF
		Dim renderer As New HtmlToPdf()

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

		' Save the PDF to a file
		Dim pdfFilePath As String = "UniqueUserNames.pdf"
		pdf.SaveAs(pdfFilePath)

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

	Private Shared Function BuildHtmlDocument(ByVal uniqueUserNames As HashSet(Of String)) As String
		' Build an HTML document with unique user names
		Dim htmlDocument As String = "<html><body><ul>"
		For Each userName In uniqueUserNames
			htmlDocument &= $"<li>{userName}</li>"
		Next userName
		htmlDocument &= "</ul></body></html>"
		Return htmlDocument
	End Function
End Class
$vbLabelText   $csharpLabel

W powyższym przykładzie kodu zapisujemy unikalne nazwy użytkowników pobrane z tablicy przy użyciu obiektu HashSet o nazwie uniqueUserNames. HashSet automatycznie eliminuje duplikaty. Następnie stworzymy nieuporządkowaną listę tych różnych nazw użytkowników w dokumencie PDF przy użyciu IronPDF. Aby dowiedzieć się więcej o kodzie, sprawdź tworzenie pliku PDF za pomocą HTML.

WYNIK

HashSet C# (Jak to działa dla programistów): Rysunek 3 – Wynik: UniqueUserNames.PDF

Wnioski

Podsumowując, struktura danych HashSet w języku C# jest skutecznym narzędziem do organizowania zbiorów odrębnych elementów. W połączeniu z IronPDF stwarza to nowe możliwości tworzenia dynamicznych, unikalnych i zoptymalizowanych pod kątem wydajności dokumentów PDF.

W podanym przykładzie pokazaliśmy, jak używać HashSet do zagwarantowania unikalności danych podczas tworzenia dokumentów PDF za pomocą IronPDF. Tworzenie solidnych i wydajnych aplikacji w języku C# może zyskać dzięki połączeniu HashSet i IronPDF, niezależnie od tego, czy pracujesz nad deduplikacją danych, raportowaniem czy zarządzaniem treścią dynamiczną. W miarę zgłębiania tematu weź pod uwagę wiele kontekstów, w których możesz wykorzystać tę kombinację, aby poprawić użyteczność i funkcjonalność swoich aplikacji.

Wersja $799 Lite programu IronPDF obejmuje stałą licencję, opcje aktualizacji oraz roczną pomoc techniczną. Przez cały okres próbny z znakiem wodnym na licencji, aby dowiedzieć się więcej o cenie, licencjonowaniu i bezpłatnej wersji próbnej IronPDF. Więcej informacji na temat Iron Software można znaleźć na stronie internetowej Iron Software.

Często Zadawane Pytania

Jak zapewnić unikalność danych podczas generowania dokumentów PDF w języku C#?

Przed wygenerowaniem dokumentu PDF można użyć zestawu HashSet do przechowywania unikalnych elementów danych, takich jak nazwy użytkowników. Zapewnia to usunięcie zduplikówanych wpisów, co pozwala uzyskać bardziej przejrzystą i dokładniejszą zawartość pliku PDF.

Jakie są zalety korzystania z HashSet w IronPDF?

Wykorzystanie HashSet w połączeniu z IronPDF pozwala na efektywne zarządzanie unikalnymi danymi podczas tworzenia plików PDF. HashSet zapewnia unikalność danych, a IronPDF wyróżnia się w konwersji treści HTML do formatu PDF, zachowując układ i style.

Jak przekonwertować zawartość HTML do formatu PDF w języku C#?

Możesz konwertować zawartość HTML do formatu PDF w języku C#, korzystając z metody RenderHtmlAsPdf biblioteki IronPDF. Metoda ta pozwala na bezpośrednią konwersję ciągów HTML do plików PDF, zachowując oryginalny układ i styl.

Jakie operacje obsługuje HashSet w języku C#?

HashSet w języku C# obsługuje szereg operacji na zbiorach, takich jak UnionWith, IntersectWith, ExceptWith i SymmetricExceptWith, które ułatwiają wydajną manipulację danymi i porównywanie zbiorów.

Jak mogę zintegrować HashSet z tworzeniem dokumentów PDF?

Aby zintegrować HashSet z tworzeniem dokumentów PDF, użyj HashSet do zarządzania danymi i filtrowania ich pod kątem unikalności przed przekazaniem ich do IronPDF w celu wygenerowania ostatecznego dokumentu PDF.

Jaka jest rola HashSet w dynamicznym zarządzaniu treścią?

W dynamicznym zarządzaniu treścią HashSet odgrywa kluczową rolę, zapewniając unikalność danych, co jest niezbędne w zadaniach takich jak generowanie dokumentów, raportowanie i utrzymanie integralności danych.

Jak zainstalować IronPDF w projekcie C#?

Możesz zainstalować IronPDF w projekcie C# za pomocą menedżera pakietów NuGet, używając polecenia: Install-Package IronPdf, lub za pomocą interfejsu CLI .NET, używając: dotnet add package IronPdf.

Czy HashSet może poprawić wydajność aplikacji w języku C#?

Tak, HashSet może znacznie poprawić wydajność aplikacji napisanych w języku C#, zapewniając stałą złożoność czasową dla podstawowych operacji, takich jak wstawianie, usuwanie i wyszukiwanie, co sprawia, że jest on wydajny w zarządzaniu dużymi zbiorami danych.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie