.NET ヘルプ

HashSet C# (開発者向けの動作方法)

更新済み 3月 6, 2024
共有:

イントロダクション

C#でのプログラミングは柔軟で、様々なタスクを効果的に管理するための多数のデータ構造を提供します。 について ハッシュセット は、基本的な操作に対してコンスタントタイムの平均複雑度を提供する強力なデータ構造の一つであり、異なるコンポーネントを備えています。 以下のテキストを日本語に翻訳します:

この記事では、C#のHashSetの使用方法と、その使用例について考察します。 IronPDF、PDFドキュメントを操作するための強力なライブラリ。

HashSet C# の使用方法

  1. 新しいコンソールアプリプロジェクトを作成します。

  2. C#でHashSetのオブジェクトを作成する。 HashSetにデフォルト値を追加します。

  3. 追加する際に、HashSetは要素が存在するかどうかをチェックすることによって自動的に重複する要素を削除します。

  4. ハッシュセットを処理する際、一意の要素を一つずつ処理します。

  5. 結果を表示してオブジェクトを破棄してください。

C#におけるHashSetの理解

C#のHashSetは、高性能なセット操作を提供するように設計されています。 HashSet は、重複する要素を防ぐため、一意のデータセットを保持する必要がある状況で使用するのに最適なコレクションです。 それは System.Assortments.Hash tables に含まれており、C# のジェネリック名前空間の基盤であり、高速な挿入、削除、より迅速な検索およびルックアップ操作を提供します。 HashSetの要素から適切な部分集合を見つけることもできます。 C#では、標準的な集合操作を簡単に実行できるHashSetの操作メソッドを使用します。 HashSetクラスは、セット操作メソッドを提供します。

以下はHashSetのC#での使用例のいくつかです:

初期化と基本操作

HashSetを生成し、エントリの追加、削除、存在確認などの基本的な操作を行います。

// set operations 
HashSet<int> numbers = new HashSet<int>();
// Add elements
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Remove an element, predicate function
numbers.Remove(2);
// Check for membership or duplicate element
bool containsThree = numbers.Contains(3);
// set operations 
HashSet<int> numbers = new HashSet<int>();
// Add elements
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Remove an element, predicate function
numbers.Remove(2);
// Check for membership or duplicate element
bool containsThree = numbers.Contains(3);
' set operations 
Dim numbers As New HashSet(Of Integer)()
' Add elements
numbers.Add(1)
numbers.Add(2)
numbers.Add(3)
' Remove an element, predicate function
numbers.Remove(2)
' Check for membership or duplicate element
Dim containsThree As Boolean = numbers.Contains(3)
VB   C#

コレクションによる初期化

既存のコレクションをハッシュセットの開始点として使用すると、重複は直ちに排除されます。

List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 }; // all the elements
HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);
List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 }; // all the elements
HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);
Dim duplicateNumbers As New List(Of Integer) From {1, 2, 2, 3, 3, 4} ' all the elements
Dim uniqueNumbers As New HashSet(Of Integer)(duplicateNumbers)
VB   C#

別のHashSetとの統合

UnionWith 関数を使用して、二つの HashSet インスタンスを組み合わせ、両方のセットから異なるアイテムを組み合わせた新しいセットを作成します。

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // set1 now contains { 1, 2, 3, 4, 5 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // set1 now contains { 1, 2, 3, 4, 5 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.UnionWith(set2) ' set1 now contains { 1, 2, 3, 4, 5 }
VB   C#

別のHashSetとの交差

IntersectWith 関数を使用して、2 つの HashSet インスタンス間の共通部分を特定します。

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.IntersectWith(set2); // set1 now contains { 3 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.IntersectWith(set2); // set1 now contains { 3 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.IntersectWith(set2) ' set1 now contains { 3 }
VB   C#

別のハッシュセットとの違い

ExceptWith関数を使用して、一つのHashSetにあるが別のHashSetにはない要素を見つけます。

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.ExceptWith(set2); // set1 now contains { 1, 2 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.ExceptWith(set2); // set1 now contains { 1, 2 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.ExceptWith(set2) ' set1 now contains { 1, 2 }
VB   C#

部分集合またはスーパーセットのチェック:

IsSubsetOf および IsSupersetOf メソッドを使用することで、特定の HashSet インスタンスが他のもののサブセットまたはスーパーセットであるかどうかを判別できます。

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3 };
bool isSubset = set2.IsSubsetOf(set1); // returns true
bool isSuperset = set1.IsSupersetOf(set2); // returns true
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3 };
bool isSubset = set2.IsSubsetOf(set1); // returns true
bool isSuperset = set1.IsSupersetOf(set2); // returns true
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {2, 3}
Dim isSubset As Boolean = set2.IsSubsetOf(set1) ' returns true
Dim isSuperset As Boolean = set1.IsSupersetOf(set2) ' returns true
VB   C#

対称差

対称的ExceptWith技法を使用して、対称差を求める (一方のセットには存在するが、両方には存在しない要素).

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.SymmetricExceptWith(set2); // set1 now contains { 1, 2, 4, 5 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.SymmetricExceptWith(set2); // set1 now contains { 1, 2, 4, 5 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.SymmetricExceptWith(set2) ' set1 now contains { 1, 2, 4, 5 }
VB   C#

IronPDF (アイアンPDF)

プログラマーはC#言語を使用して、IronPDFを活用し、PDFドキュメントを作成、編集、および修正することができます。 IronPDF .NET PDF ライブラリ。 アプリケーションは、PDFファイルに対してさまざまな操作を可能にする幅広いツールと機能を提供します。これには、HTMLから新しいPDFを作成する、HTMLをPDFに変換する、PDFドキュメントを結合または分割する、既存のPDFにテキスト、写真、およびその他のデータを注釈付けすることが含まれます。 IronPDFについて詳しく知るには、こちらを参照してください ドキュメント.

IronPDFの機能

  • HTMLからPDFへの変換:IronPDFを使用すると、ファイル、URL、HTMLコード文字列を含むあらゆる種類のHTMLデータをPDFドキュメントに変換することができます。
  • PDF生成:C#プログラミング言語を使用して、テキスト、画像、その他のオブジェクトをプログラムでPDF文書に追加できます。
  • PDF操作: IronPDFはPDFファイルを複数のファイルに分割し、既存のPDFファイルを編集することができます。 複数のPDFファイルを単一のファイルに結合することができます。
  • PDF フォーム: このライブラリはユーザーがPDFフォームを作成および記入することを可能にするため、フォームデータを収集して処理する必要があるシナリオで役立ちます。

  • セキュリティ機能: IronPDFは、PDF文書の暗号化、パスワードおよび権限セキュリティを提供します。

IronPDF をインストール

IronPDFライブラリを取得する 次回のパッチにはそれが必要です。 これを行うには、次のコードをパッケージ マネージャーに入力します:

Install-Package IronPDF 
//or 
dotnet add package IronPdf

HashSet C#(開発者向けの動作方法): 図1 - パッケージマネージャーコンソールを使用してIronPDFライブラリをインストールし、次のコマンドを入力します:「Install-Package IronPDF」または「dotnet add package IronPdf」。

別のオプションとして、NuGet Package Managerを使用して「IronPDF」パッケージを探すことができます。 IronPDFに関連するすべてのNuGetパッケージから、このリストから必要なパッケージを選択してダウンロードできます。

HashSet C# (開発者向けの仕組み)図2 - NuGetパッケージマネージャーを使用してIronPDFライブラリをインストールできます。 Browseタブで「ironpdf」パッケージを検索し、最新バージョンのIronPDFを選択してインストールしてください。

IronPDFでのHashSet

C#環境内で、IronPDFはPDFドキュメントの操作を容易にする強力なライブラリです。 異なるデータの表現と効果的なドキュメント作成が重要な状況では、HashSetの効率とIronPDFのドキュメント操作能力を組み合わせることで、創造的なソリューションが得られるかもしれません。

IronPDFを使用したHashSetの利点

  • データ冗長性の削減:HashSetを使用することで、重複のない要素のみが保持されるため、データの重複を防ぐことができます。 大規模なデータセットを扱う際に重複情報を削除するために、これは非常に役立ちます。
  • 効果的な検索: HashSetを使用すると、挿入、削除、および検索などの基本操作が定数時間平均複雑度で実行される可能性があります。 異なるサイズのデータセットを扱う際には、このようなパフォーマンスが非常に重要です。

  • ドキュメント作成の簡略化: IronPDF は C# PDF ドキュメント作成プロセスを効率化します。 HashSetをIronPDFと統合することで、PDF用のオリジナルで動的なコンテンツを迅速かつ効果的に作成するプロセスを確立することができます。

    では、次に、IronPDFとHashSetを使用することで役立つ実際のシナリオを見てみましょう。

ユニークなデータを使用してPDFを生成

using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
class PdfGenerator
{
    static void Main()
    {
        // Sample user names
        string [] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };
        // Using HashSet to store 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
        IronPdf.HtmlToPdf renderer = new IronPdf.HtmlToPdf();
        PdfDocument 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;
using System.IO;
class PdfGenerator
{
    static void Main()
    {
        // Sample user names
        string [] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };
        // Using HashSet to store 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
        IronPdf.HtmlToPdf renderer = new IronPdf.HtmlToPdf();
        PdfDocument 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
Imports System.IO
Friend Class PdfGenerator
	Shared Sub Main()
		' Sample user names
		Dim userNames() As String = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" }
		' Using HashSet to store 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 IronPdf.HtmlToPdf()
		Dim pdf As PdfDocument = 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
VB   C#

上記のコード例では、uniqueUserNames という HashSet を使用して配列から取得した一意のユーザー名を保存しています。 HashSetは自動的に重複を排除します。 次に、IronPDFを使用してこれらの異なるユーザー名の順序なしリストをPDFドキュメントに作成します。 詳細情報については、コードの確認をご覧ください。 これ.

出力

C#のHashSet(開発者向けの使い方):図3 - 出力:UniqueUserNames.pdf

結論

まとめると、C#のHashSetデータ構造は、異なるアイテムのセットを整理するための効果的なツールです。 これは、IronPDFと組み合わせることで、動的でユニークかつパフォーマンス最適化されたPDFドキュメント作成の新しい機会を生み出します。

私たちはHashSetを使用してデータの一意性を保証する方法を説明しました。 IronPDF 指定された例でPDFドキュメントを作成するために。 強力で効果的なC#アプリケーションを構築する際には、データの重複排除、レポート作成、または動的コンテンツの管理を行う際に、HashSetとIronPDFの組み合わせが役立つことがあります。 さらに調査を進める際には、この組み合わせを使用してアプリケーションの使いやすさと機能性を向上させるために、さまざまな状況を考慮に入れてください。

IronPDFの$749 Liteバージョンには、永久ライセンス、アップグレードオプション、および1年間のソフトウェアサポートが含まれています。 透かしの入った 試用期間 IronPDFの価格、ライセンス、および無料試用版の詳細を確認するために。 こちらをご覧ください ページ アイアンソフトウェアに関する詳細情報については。

< 以前
C# nameof(開発者向けの動作方法)
次へ >
C# 配列の長さ(開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >