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
このコードでは、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());
}
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
このコードでは、一意の 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}");
}
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
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
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
このコードでは、PDF を読み込み、テキストを抽出して行に分割し、FindAll を使用して"チェーン リング ID"が記載されているすべての行を検索しました。

これは、実際のシナリオで Find メソッドをIronPDFとともに使用する方法の基本的な例です。 これは、C#とその強力なライブラリを使用して、プログラミングタスクをより簡単かつ効率的にするためのユーティリティと多様性を示しています。
結論
このチュートリアルでは、C# の Find メソッドとその関連メソッドである FindLastIndex、および 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 処理機能を提供し、ドキュメント関連タスクの効率を向上させます。




