フッターコンテンツにスキップ
開発者向けアップデート

C# Find (開発者向けの仕組み)

C# の便利な Find 関数についてのチュートリアルへようこそ。 コードを書くプロセスを効率化できる強力な機能に出会ったばかりです。 したがって、経験豊富なコーダーであれ、初めての方であれ、このチュートリアルはすべての要素を案内してくれます。

Findの基本

基本的に、Find は、指定された条件を満たすコレクション、配列、またはリスト内の最初の要素を見つけるための関数です。 述語って何ですか? プログラミングにおいて、述語はコレクション内の要素に対して定義された特定の条件をテストする関数です。

それでは、公開クラスの例を見てみましょう。

public class BikePart
{
    public string Id { get; set; } // Property to identify the bike part

    // Override the Equals method to specify how to compare two BikePart objects
    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is BikePart))
            return false;

        return this.Id == ((BikePart)obj).Id;
    }

    // Override GetHashCode for hashing BikePart objects
    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    // Override ToString to return a custom string representation of the object
    public override string ToString()
    {
        return "BikePart ID: " + this.Id;
    }
}
public class BikePart
{
    public string Id { get; set; } // Property to identify the bike part

    // Override the Equals method to specify how to compare two BikePart objects
    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is BikePart))
            return false;

        return this.Id == ((BikePart)obj).Id;
    }

    // Override GetHashCode for hashing BikePart objects
    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    // Override ToString to return a custom string representation of the object
    public override string ToString()
    {
        return "BikePart ID: " + this.Id;
    }
}
Public Class BikePart
	Public Property Id() As String ' -  Property to identify the bike part

	' Override the Equals method to specify how to compare two BikePart objects
	Public Overrides Function Equals(ByVal obj As Object) As Boolean
		If obj Is Nothing OrElse Not (TypeOf obj Is BikePart) Then
			Return False
		End If

		Return Me.Id = DirectCast(obj, BikePart).Id
	End Function

	' Override GetHashCode for hashing BikePart objects
	Public Overrides Function GetHashCode() As Integer
		Return Me.Id.GetHashCode()
	End Function

	' Override ToString to return a custom string representation of the object
	Public Overrides Function ToString() As String
		Return "BikePart ID: " & Me.Id
	End Function
End Class
$vbLabelText   $csharpLabel

このコードでは、BikePart がパブリッククラスであり、それは各バイク部品を識別するためのパブリックな文字列 ID を持っています。 バイク部品の ID をきれいに印刷するために ToString メソッドをオーバーライドし、比較のために Equals および GetHashCode メソッドもオーバーライドしました。

述語を用いたFindの利用

私たちの BikePart クラスができたので、バイク部品のリストを作成し、その ID に基づいて特定の部品を見つけるために Find を使用できます。 次の例を考えてみましょう。

using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };
    BikePart chainRingPart = bikeParts.Find(findChainRingPredicate);

    // Print the found BikePart's ID to the console
    Console.WriteLine(chainRingPart.ToString());
}
using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };
    BikePart chainRingPart = bikeParts.Find(findChainRingPredicate);

    // Print the found BikePart's ID to the console
    Console.WriteLine(chainRingPart.ToString());
}
Imports System
Imports System.Collections.Generic

Public Shared Sub Main()
	' Create a list of BikePart objects
	Dim bikeParts As New List(Of BikePart) From {
		New BikePart With {.Id = "Chain Ring ID"},
		New BikePart With {.Id = "Crank Arm ID"},
		New BikePart With {.Id = "Regular Seat ID"},
		New BikePart With {.Id = "Banana Seat ID"}
	}

	' Define a predicate to find a BikePart with a specific ID
	Dim findChainRingPredicate As Predicate(Of BikePart) = Function(bp As BikePart)
		Return bp.Id = "Chain Ring ID"
	End Function
	Dim chainRingPart As BikePart = bikeParts.Find(findChainRingPredicate)

	' Print the found BikePart's ID to the console
	Console.WriteLine(chainRingPart.ToString())
End Sub
$vbLabelText   $csharpLabel

このコードでは、ユニークな ID を持つ4つの BikePart オブジェクトをインスタンス化します。 次に、バイク部品が"Chain Ring ID"を持っているかを確認するプレディケート findChainRingPredicate を作成します。 最後に、定義したプレディケートを使用してバイク部品のリストで Find を呼び出し、見つかった部品の ID をコンソールに印刷します。

述語パラメータの理解

私たちの Find メソッドにおける Predicate match パラメータについて疑問に思うかもしれません。 これは、Find メソッドが要素を返す条件を定義する場所です。 私たちの場合、Find メソッドが"Chain Ring ID"に一致する最初の要素を返すことを望みました。

プレディケートで定義された条件を満たす要素がない場合、Find メソッドはデフォルトの値を返します。 例えば、整数の配列を扱っていて、プレディケートが一致を見つけない場合、Find メソッドは C# の整数のデフォルト値である '0' を返します。

線形探索の原則

重要なのは、Find 関数が配列、リスト、またはコレクション全体で線形検索を行うことです。 これは最初の要素から始まり、次の各要素を順番に調べて、述語を満たす最初の要素の出現を見つけるまで続きます。

場合によっては、述語を満たす最初の要素ではなく、最後の要素を見つけたいことがあります。 この目的のために、C# は FindLast 関数を提供します。

FindIndexFindLastIndex

指定した条件に一致する要素の最初の出現箇所を見つけるのに Find が役立つように、C# もまた、条件に一致する最初と最後の要素のインデックスを提供する FindIndex および FindLastIndex メソッドを提供します。

例を試してみましょう:

using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Find the index of the first and last occurrence of the specified BikePart
    int firstChainRingIndex = bikeParts.FindIndex(findChainRingPredicate);
    int lastChainRingIndex = bikeParts.FindLastIndex(findChainRingPredicate);

    // Print the indices to the console
    Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}");
    Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}");
}
using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Find the index of the first and last occurrence of the specified BikePart
    int firstChainRingIndex = bikeParts.FindIndex(findChainRingPredicate);
    int lastChainRingIndex = bikeParts.FindLastIndex(findChainRingPredicate);

    // Print the indices to the console
    Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}");
    Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}");
}
Imports System
Imports System.Collections.Generic

Public Shared Sub Main()
	' Create a list of BikePart objects with an additional duplicate entry
	Dim bikeParts As New List(Of BikePart) From {
		New BikePart With {.Id = "Chain Ring ID"},
		New BikePart With {.Id = "Crank Arm ID"},
		New BikePart With {.Id = "Regular Seat ID"},
		New BikePart With {.Id = "Banana Seat ID"},
		New BikePart With {.Id = "Chain Ring ID"}
	}

	' Define a predicate to find a BikePart with a specific ID
	Dim findChainRingPredicate As Predicate(Of BikePart) = Function(bp As BikePart)
		Return bp.Id = "Chain Ring ID"
	End Function

	' Find the index of the first and last occurrence of the specified BikePart
	Dim firstChainRingIndex As Integer = bikeParts.FindIndex(findChainRingPredicate)
	Dim lastChainRingIndex As Integer = bikeParts.FindLastIndex(findChainRingPredicate)

	' Print the indices to the console
	Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}")
	Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}")
End Sub
$vbLabelText   $csharpLabel

FindAll の力

名前が示すように、FindAll メソッドはプレディケートを満たすコレクション内のすべての要素を取得します。 特定の条件に基づいて要素をフィルタリングする必要がある場合に使用されます。 FindAll メソッドは一致するすべての要素を含む新しいリストを返します。

以下がコード例です:

using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find all BikeParts with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Use FindAll to get all matching BikePart objects
    List<BikePart> chainRings = bikeParts.FindAll(findChainRingPredicate);

    // Print the count and details of each found BikePart
    Console.WriteLine($"Found {chainRings.Count} Chain Rings:");
    foreach (BikePart chainRing in chainRings)
    {
        Console.WriteLine(chainRing.ToString());
    }
}
using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find all BikeParts with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Use FindAll to get all matching BikePart objects
    List<BikePart> chainRings = bikeParts.FindAll(findChainRingPredicate);

    // Print the count and details of each found BikePart
    Console.WriteLine($"Found {chainRings.Count} Chain Rings:");
    foreach (BikePart chainRing in chainRings)
    {
        Console.WriteLine(chainRing.ToString());
    }
}
Imports System
Imports System.Collections.Generic

Public Shared Sub Main()
	' Create a list of BikePart objects with an additional duplicate entry
	Dim bikeParts As New List(Of BikePart) From {
		New BikePart With {.Id = "Chain Ring ID"},
		New BikePart With {.Id = "Crank Arm ID"},
		New BikePart With {.Id = "Regular Seat ID"},
		New BikePart With {.Id = "Banana Seat ID"},
		New BikePart With {.Id = "Chain Ring ID"}
	}

	' Define a predicate to find all BikeParts with a specific ID
	Dim findChainRingPredicate As Predicate(Of BikePart) = Function(bp As BikePart)
		Return bp.Id = "Chain Ring ID"
	End Function

	' Use FindAll to get all matching BikePart objects
	Dim chainRings As List(Of BikePart) = bikeParts.FindAll(findChainRingPredicate)

	' Print the count and details of each found BikePart
	Console.WriteLine($"Found {chainRings.Count} Chain Rings:")
	For Each chainRing As BikePart In chainRings
		Console.WriteLine(chainRing.ToString())
	Next chainRing
End Sub
$vbLabelText   $csharpLabel

IronPDFを取り入れる

C#のFind知識を活用できる重要な分野は、IronPDFという強力なC#ライブラリを使用したPDFコンテンツの操作です。

様々なバイク部品に関する情報を含むPDFドキュメントを扱っているとします。 しばしば、このコンテンツ内で特定の部品を見つける必要があります。 IronPDFとC# Findメソッドが組み合わさって、強力な解決策を提供します。

最初に、IronPDF を使用して PDF からテキストを抽出し、その後、抽出されたテキスト内の特定の部分を見つけるために以前学んだ Find または FindAll メソッドを使用できます。

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

public class Program
{
    public static void Main()
    {
        // Load and extract text from a PDF document
        PdfDocument pdf = PdfDocument.FromFile(@"C:\Users\Administrator\Desktop\bike.pdf");
        string pdfText = pdf.ExtractAllText();

        // Split the extracted text into lines
        List<string> pdfLines = pdfText.Split('\n').ToList();

        // Define a predicate to find lines that contain a specific text
        Predicate<string> findChainRingPredicate = (string line) => { return line.Contains("Chain Ring ID"); };

        // Use FindAll to get all lines containing the specified text
        List<string> chainRingLines = pdfLines.FindAll(findChainRingPredicate);

        // Print the count and content of each found line
        Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':");
        foreach (string line in chainRingLines)
        {
            Console.WriteLine(line);
        }
    }
}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // Load and extract text from a PDF document
        PdfDocument pdf = PdfDocument.FromFile(@"C:\Users\Administrator\Desktop\bike.pdf");
        string pdfText = pdf.ExtractAllText();

        // Split the extracted text into lines
        List<string> pdfLines = pdfText.Split('\n').ToList();

        // Define a predicate to find lines that contain a specific text
        Predicate<string> findChainRingPredicate = (string line) => { return line.Contains("Chain Ring ID"); };

        // Use FindAll to get all lines containing the specified text
        List<string> chainRingLines = pdfLines.FindAll(findChainRingPredicate);

        // Print the count and content of each found line
        Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':");
        foreach (string line in chainRingLines)
        {
            Console.WriteLine(line);
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Class Program
	Public Shared Sub Main()
		' Load and extract text from a PDF document
		Dim pdf As PdfDocument = PdfDocument.FromFile("C:\Users\Administrator\Desktop\bike.pdf")
		Dim pdfText As String = pdf.ExtractAllText()

		' Split the extracted text into lines
		Dim pdfLines As List(Of String) = pdfText.Split(ControlChars.Lf).ToList()

		' Define a predicate to find lines that contain a specific text
		Dim findChainRingPredicate As Predicate(Of String) = Function(line As String)
			Return line.Contains("Chain Ring ID")
		End Function

		' Use FindAll to get all lines containing the specified text
		Dim chainRingLines As List(Of String) = pdfLines.FindAll(findChainRingPredicate)

		' Print the count and content of each found line
		Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':")
		For Each line As String In chainRingLines
			Console.WriteLine(line)
		Next line
	End Sub
End Class
$vbLabelText   $csharpLabel

このコードでは、PDF をロードし、テキストを抽出し、行に分割し、FindAll を使用して"Chain Ring ID"に言及しているすべての行を見つけました。

 VB.NET で PDF ファイルを見る方法: Figure 1

これは、Find メソッドが IronPDF と共に実用的なシナリオでどのように使用されるかの基本的な例です。 これは、C#とその強力なライブラリを使用して、プログラミングタスクをより簡単かつ効率的にするためのユーティリティと多様性を示しています。

結論

このチュートリアルでは、C# の Find メソッドとその関連する FindAll について詳しく掘り下げました。 それらの使用法を探り、いくつかのコード例を探索し、それらが最も効果的な状況を明らかにしました。

また、IronPDFライブラリを使用したPDF操作の世界にも一歩踏み出しました。 同様に、PDF ドキュメント内のコンテンツの抽出と検索における Find メソッド知識の実際の応用を見ました。

IronPDFはIronPDF無料トライアルを提供しており、その機能を探求し、C#プロジェクトにどのように役立つかを確認する絶好の機会を提供しています。 トライアル後に IronPDF の使用を続けることを決めた場合、ライセンスは $999 から始まります。

よくある質問

C# の Find 関数は開発者にとってどのように機能しますか?

C# の Find 関数は、開発者が述語で定義された特定の条件を満たす、コレクション、配列、リスト内の最初の要素を見つけることを可能にします。この機能はコーディングプロセスを合理化するのに役立ちます。

述語とは何であり、C# でどのように使用されますか?

C# の述語は、特定の条件を持つメソッドを表すデリゲートです。Find のようなメソッドで使用され、コレクション内の各要素をテストし、条件を満たす要素を返します。

C# でカスタムクラスと Find メソッドを使用できますか?

はい、クラスの要素の検索条件と一致する述語を定義することで、カスタムクラスと Find メソッドを使用できます。たとえば、特定のプロパティ値を持つオブジェクトを見つけることなどです。

Find メソッドで条件に一致する要素が見つからない場合はどうなりますか?

Find メソッドで述語に一致する要素がない場合、参照型の場合はnull、値型の場合は0といったデフォルト値を返します。

C# の Find と FindAll の違いは何ですか?

Find メソッドは述語に一致する最初の要素を返すのに対し、FindAll は述語の条件を満たすすべての要素のリストを返します。

FindIndex と FindLastIndex メソッドはどのように異なりますか?

FindIndex は述語に一致する最初の要素のインデックスを返し、FindLastIndex は条件に一致する最後の要素のインデックスを返します。

C# の Find をテキスト検索用に PDF ライブラリと統合する方法は?

PDF ライブラリを使用することで、PDF からテキストを抽出し、そのテキスト内で特定の内容を検索するために Find メソッドを利用できます。これにより、ドキュメント処理が効果的になります。

述語を使用して要素のプロパティで検索することは可能ですか?

はい、特定の ID や属性を持つオブジェクトを見つけるなどのために、要素のプロパティに基づいて述語を定義することができます。

大規模なデータコレクションに対する Find メソッドの効率は?

Find メソッドは線形検索を行い、順番に各要素をチェックします。単純とはいえ、非常に大きなコレクションでは O(n) の複雑さのため、最も効率的でない場合があります。

C# 開発者にとって PDF ライブラリの利点は何ですか?

PDF ライブラリは、C# を使用して PDF コンテンツを簡単に抽出、操作、検索するための強力な PDF 処理機能を提供し、ドキュメント関連タスクの効率を向上させます。

Jacob Mellor、Ironチームの最高技術責任者(CTO)
最高技術責任者(CTO)

ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。

彼の主要なIronPDFとIron Suite .NETライブラリは、世界中で3000万以上のNuGetインストールを達成し、彼の基礎となるコードは世界中で使用されている開発者ツールに力を与え続けています。25年の商業経験と41年のコーディングの専門知識を持つJacobは、次世代の技術リーダーを指導しながら、エンタープライズグレードのC#、Java、Python PDFテクノロジーにおけるイノベーションの推進に注力しています。

アイアンサポートチーム

私たちは週5日、24時間オンラインで対応しています。
チャット
メール
電話してね