フッターコンテンツにスキップ
.NETヘルプ

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;
    }
}
$vbLabelText   $csharpLabel

このコードでは、BikePart はパブリック クラスであり、自転車の各パーツを識別するためのパブリック文字列 ID が含まれています。 自転車の部品の ID を適切に印刷するために、ToString メソッドをオーバーライドしました。また、比較のために、Equals メソッドと GetHashCode メソッドもオーバーライドしました。

述語を用いたFindの利用

BikePart クラスが作成されたので、自転車の部品のリストを作成し、 Findを使用して ID に基づいて特定の部品を見つけることができます。 次の例を考えてみましょう。

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());
}
$vbLabelText   $csharpLabel

このコードでは、一意の ID を持つ 4 つの BikePart オブジェクトをインスタンス化します。 次に、自転車の部品に"Chain Ring ID"という ID があるかどうかを確認する述語 findChainRingPredicate を作成します。 最後に、定義した述語を使用して自転車部品のリストに対して Find を呼び出し、見つかった部品の ID をコンソールに出力します。

述語パラメータの理解

Find メソッドの述語一致パラメータについて疑問に思われるかもしれません。 ここで、Find メソッドが要素を返す条件を定義します。 私たちの場合、Find メソッドで"チェーン リング ID"に一致する最初の要素を返す必要がありました。

述語で定義された条件を満たす要素がない場合、Find メソッドはデフォルト値を返します。 たとえば、整数の配列を操作していて、述語が一致するものを見つけられない場合、Find メソッドは C# の整数の既定値である '0' を返します。

線形探索の原則

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

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

FindIndex および FindLastIndex

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}");
}
$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());
    }
}
$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);
        }
    }
}
$vbLabelText   $csharpLabel

このコードでは、PDF を読み込み、テキストを抽出して行に分割し、FindAll を使用して"チェーン リング ID"が記載されているすべての行を検索しました。

VB .NETで PDF ファイルを表示する方法: 図 1

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

結論

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

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

IronPDFはIronPDF無料トライアルを提供しており、その機能を探求し、C#プロジェクトにどのように役立つかを確認する絶好の機会を提供しています。 試用期間後にIronPDF を引き続き使用する場合は、ライセンスは $799 から開始されます。

よくある質問

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テクノロジーにおけるイノベーションの推進に注力しています。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me