List<T>.FindLastIndex メソッド

定義

List<T> またはその一部分から、指定した述語によって定義される条件に一致する要素を検索し、最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by a specified predicate, and returns the zero-based index of the last occurrence within the List<T> or a portion of it.

オーバーロード

FindLastIndex(Predicate<T>)

List<T> 全体から、指定した述語によって定義される条件に一致する要素を検索し、最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire List<T>.

FindLastIndex(Int32, Predicate<T>)

List<T> のうち、先頭の要素から指定したインデックスまでの範囲の中で、指定した述語によって定義される条件に一致する要素を検索し、そのうち最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List<T> that extends from the first element to the specified index.

FindLastIndex(Int32, Int32, Predicate<T>)

List<T> のうち、指定したインデックスで終わり、指定した要素数が含まれる範囲の中で、指定した述語によって定義される条件に一致する要素を検索し、そのうち最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List<T> that contains the specified number of elements and ends at the specified index.

FindLastIndex(Predicate<T>)

List<T> 全体から、指定した述語によって定義される条件に一致する要素を検索し、最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire List<T>.

public:
 int FindLastIndex(Predicate<T> ^ match);
public int FindLastIndex (Predicate<T> match);
member this.FindLastIndex : Predicate<'T> -> int
Public Function FindLastIndex (match As Predicate(Of T)) As Integer

パラメーター

match
Predicate<T>

検索する要素の条件を定義する Predicate<T> デリゲート。The Predicate<T> delegate that defines the conditions of the element to search for.

戻り値

match で定義された条件と一致する要素が存在する場合、最もインデックス番号の大きい要素の 0 から始まるインデックス。それ以外の場合は -1。The zero-based index of the last occurrence of an element that matches the conditions defined by match, if found; otherwise, -1.

例外

matchnull です。match is null.

次の例は、List<T> クラスの find メソッドを示しています。The following example demonstrates the find methods for the List<T> class. List<T> クラスの例には、サンプル XML ファイルのデータを使用して、クラス Bookbook オブジェクトが含まれています。書籍 (LINQ to XML)」。The example for the List<T> class contains book objects, of class Book, using the data from the Sample XML File: Books (LINQ to XML). この例の FillList メソッドでは、 LINQ to XMLを使用して、XML から book オブジェクトのプロパティ値を解析します。The FillList method in the example uses LINQ to XML to parse the values from the XML to property values of the book objects.

次の表では、find メソッドに用意されている例について説明します。The following table describes the examples provided for the find methods.

メソッドMethod Example
Find(Predicate<T>) IDToFind 述語デリゲートを使用して、ID で書籍を検索します。Finds a book by an ID using the IDToFind predicate delegate.

C#例では、匿名デリゲートを使用します。C# example uses an anonymous delegate.
FindAll(Predicate<T>) FindComputer 述語デリゲートを使用して、Genre プロパティが "Computer" であるすべての書籍を検索します。Find all books that whose Genre property is "Computer" using the FindComputer predicate delegate.
FindLast(Predicate<T>) PubBefore2001 述語デリゲートを使用して、2001より前の発行日を持つ、コレクション内の最後のブックを検索します。Finds the last book in the collection that has a publish date before 2001, using the PubBefore2001 predicate delegate.

C#例では、匿名デリゲートを使用します。C# example uses an anonymous delegate.
FindIndex(Predicate<T>) FindComputer 述語デリゲートを使用して、最初のコンピューターブックのインデックスを検索します。Finds the index of first computer book using the FindComputer predicate delegate.
FindLastIndex(Predicate<T>) FindComputer 述語デリゲートを使用して、最後のコンピューターブックのインデックスを検索します。Finds the index of the last computer book using the FindComputer predicate delegate.
FindIndex(Int32, Int32, Predicate<T>) FindComputer 述語デリゲートを使用して、コレクションの後半にある最初のコンピューターブックのインデックスを検索します。Finds the index of first computer book in the second half of the collection, using the FindComputer predicate delegate.
FindLastIndex(Int32, Int32, Predicate<T>) FindComputer 述語デリゲートを使用して、コレクションの後半で最後のコンピューターブックのインデックスを検索します。Finds the index of last computer book in the second half of the collection, using the FindComputer predicate delegate.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Find
{
    class Program
    {
        private static string IDtoFind = "bk109";

        private static List<Book> Books = new List<Book>();
        public static void Main(string[] args)
        {
            FillList();
            
            // Find a book by its ID.
            Book result = Books.Find(
            delegate(Book bk)
            {
                return bk.ID == IDtoFind;
            }
            );
            if (result != null)
            {
                DisplayResult(result, "Find by ID: " + IDtoFind);   
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }


            // Find last book in collection published before 2001.
            result = Books.FindLast(
            delegate(Book bk)
            {
                DateTime year2001 = new DateTime(2001,01,01);
                return bk.Publish_date < year2001;
            });
            if (result != null)
            {
                DisplayResult(result, "Last book in collection published before 2001:");
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }


            // Find all computer books.
            List<Book> results = Books.FindAll(FindComputer);
            if (results.Count != 0)
            {
                DisplayResults(results, "All computer:");
            }
            else
            {
                Console.WriteLine("\nNo books found.");
            }

            // Find all books under $10.00.
            results = Books.FindAll(
            delegate(Book bk)
            {
                return bk.Price < 10.00;
            }
            );
            if (results.Count != 0)
            {
                DisplayResults(results, "Books under $10:");
            }
            else
            {
                Console.WriteLine("\nNo books found.");
            }
            

            // Find index values.
            Console.WriteLine();
            int ndx = Books.FindIndex(FindComputer);
            Console.WriteLine("Index of first computer book: {0}", ndx);
            ndx = Books.FindLastIndex(FindComputer);
            Console.WriteLine("Index of last computer book: {0}", ndx);

            int mid = Books.Count / 2;
            ndx = Books.FindIndex(mid, mid, FindComputer);
            Console.WriteLine("Index of first computer book in the second half of the collection: {0}", ndx);
            
            ndx = Books.FindLastIndex(Books.Count - 1, mid, FindComputer);
            Console.WriteLine("Index of last computer book in the second half of the collection: {0}", ndx);

        }





        // Populates the list with sample data.
        private static void FillList()
        {
            
            // Create XML elements from a source file.
            XElement xTree = XElement.Load(@"c:\temp\books.xml");

            // Create an enumerable collection of the elements.
            IEnumerable<XElement> elements = xTree.Elements();

            // Evaluate each element and set set values in the book object.
            foreach (XElement el in elements)
            {
                Book book = new Book();
                book.ID = el.Attribute("id").Value;
                IEnumerable<XElement> props = el.Elements();
                foreach (XElement p in props)
                {


                    if (p.Name.ToString().ToLower() == "author")
                    {
                        book.Author = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "title")
                    {
                        book.Title = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "genre")
                    {
                        book.Genre = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "price")
                    {
                        book.Price = Convert.ToDouble(p.Value);
                    }
                    else if (p.Name.ToString().ToLower() == "publish_date")
                    {
                        book.Publish_date = Convert.ToDateTime(p.Value);
                    }
                    else if (p.Name.ToString().ToLower() == "description")
                    {
                        book.Description = p.Value;
                    }
                }

                Books.Add(book);

            }

            DisplayResults(Books, "All books:");

        }

        // Explicit predicate delegate.
        private static bool FindComputer(Book bk)
        {

            if (bk.Genre == "Computer")
            {
                return true;
            }
        else
            {
                return false;
            }

        }

        private static void DisplayResult(Book result, string title)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", result.ID,
                result.Author, result.Title, result.Genre, result.Price,
                result.Publish_date.ToShortDateString());
            Console.WriteLine();


        }

        private static void DisplayResults(List<Book> results, string title)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            foreach (Book b in results)
            {

                Console.Write("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", b.ID,
                    b.Author, b.Title, b.Genre, b.Price,
                    b.Publish_date.ToShortDateString());
            }
            Console.WriteLine();

        }

    }

    public class Book
    {
        public string ID { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
        public string Genre { get; set; }
        public double Price { get; set; }
        public DateTime Publish_date { get; set; }
        public string Description { get; set; }
    }
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Module Module1

    Private IDToFind As String = "bk109"

    Public Books As New List(Of Book)


    Sub Main()

        FillList()

        ' Find a book by its ID.
        Dim result As Book = Books.Find(AddressOf FindID)
        If result IsNot Nothing Then
            DisplayResult(result, "Find by ID: " & IDToFind)
        Else

            Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
        End If
        Console.WriteLine()

        ' Find last book in collection that has a publish date before 2001.
        result = Books.FindLast(AddressOf PubBefore2001)
        If result IsNot Nothing Then
            DisplayResult(result, "Last book in collection published before 2001:")
        Else
            Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
        End If
        Console.WriteLine()

        ' Find all computer books.
        Dim results As List(Of Book) = Books.FindAll(AddressOf FindComputer)
        If results.Count <> 0 Then
            DisplayResults(results, "All computer books:")
        Else
            Console.WriteLine(vbCrLf & "No books found.")
        End If
        Console.WriteLine()


        ' Find all books under $10.00.
        results = Books.FindAll(AddressOf FindUnderTen)
        If results.Count <> 0 Then
            DisplayResults(results, "Books under $10:")
        Else
            Console.WriteLine(vbCrLf & "No books found.")
        End If
        Console.WriteLine()

        ' Find index values.
        Console.WriteLine()
        Dim ndx As Integer = Books.FindIndex(AddressOf FindComputer)
        Console.WriteLine("Index of first computer book: " & ndx)
        ndx = Books.FindLastIndex(AddressOf FindComputer)
        Console.WriteLine("Index of last computer book: " & ndx)

        Dim mid As Integer = Books.Count / 2
        ndx = Books.FindIndex(mid, mid, AddressOf FindComputer)
        Console.WriteLine("Index of first computer book in the second half of the collection: " & ndx)



        ndx = Books.FindLastIndex(Books.Count - 1, mid, AddressOf FindComputer)
        Console.WriteLine("Index of last computer book in the second half of the collection: " & ndx)


    End Sub



    Private Sub FillList()

        ' Create XML elements from a source file.
        Dim xTree As XElement = XElement.Load("c:\temp\books.xml")

        ' Create an enumerable collection of the elements.
        Dim elements As IEnumerable(Of XElement) = xTree.Elements

        ' Evaluate each element and set values in the book object.
        For Each el As XElement In elements
            Dim Book As New Book()
            Book.ID = el.Attribute("id").Value
            Dim props As IEnumerable(Of XElement) = el.Elements
            For Each p As XElement In props
                If p.Name.ToString.ToLower = "author" Then
                    Book.Author = p.Value
                End If
                If p.Name.ToString.ToLower = "title" Then
                    Book.Title = p.Value
                End If
                If p.Name.ToString.ToLower = "genre" Then
                    Book.Genre = p.Value
                End If
                If p.Name.ToString.ToLower = "price" Then
                    Book.Price = Convert.ToDouble(p.Value)
                End If
                If p.Name.ToString.ToLower = "publish_date" Then
                    Book.Publish_date = Convert.ToDateTime(p.Value)
                End If
                If p.Name.ToString.ToLower = "description" Then
                    Book.Description = p.Value
                End If
            Next
            Books.Add(Book)
        Next

        DisplayResults(Books, "All books:")
        Console.WriteLine()

    End Sub

    ' Predicate delegates for
    ' Find and FindAll methods.
    Private Function FindID(ByVal bk As Book) As Boolean
        If bk.ID = IDToFind Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function FindComputer(ByVal bk As Book) As Boolean
        If bk.Genre = "Computer" Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function FindUnderTen(ByVal bk As Book) As Boolean
        Dim tendollars As Double = 10.0
        If bk.Price < tendollars Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function PubBefore2001(ByVal bk As Book) As Boolean
        Dim year2001 As DateTime = New DateTime(2001, 1, 1)
        Return bk.Publish_date < year2001
    End Function
    Private Sub DisplayResult(ByVal result As Book, ByVal title As String)
        Console.WriteLine()
        Console.WriteLine(title)
        Console.WriteLine(vbLf & result.ID & vbTab & result.Author & _
                          vbTab & result.Title & vbTab & result.Genre & _
                          vbTab & result.Publish_date & vbTab & result.Price)
        Console.WriteLine()
    End Sub
    Private Sub DisplayResults(ByVal results As List(Of Book), ByVal title As String)
        Console.WriteLine()
        Console.WriteLine(title)
        For Each b As Book In results
            Console.Write(vbLf & b.ID & vbTab & b.Author & _
                              vbTab & b.Title & vbTab & b.Genre & _
                              vbTab & b.Publish_date & vbTab & b.Price)
        Next
        Console.WriteLine()
    End Sub

    Public Class Book
        Public ID As String
        Public Author As String
        Public Title As String
        Public Genre As String
        Public Price As Double
        Public Publish_date As DateTime
        Public Description As String
    End Class


End Module

注釈

List<T> は、最後の要素から後方に検索され、最初の要素で終了します。The List<T> is searched backward starting at the last element and ending at the first element.

Predicate<T> は、渡されたオブジェクトがデリゲートで定義されている条件に一致する場合に true を返すメソッドのデリゲートです。The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. 現在の List<T> の要素は、Predicate<T> デリゲートに個別に渡されます。The elements of the current List<T> are individually passed to the Predicate<T> delegate.

このメソッドは、線形検索を実行します。したがって、このメソッドは O (n) 操作です。ここで、 nCountです。This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

こちらもご覧ください

FindLastIndex(Int32, Predicate<T>)

List<T> のうち、先頭の要素から指定したインデックスまでの範囲の中で、指定した述語によって定義される条件に一致する要素を検索し、そのうち最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List<T> that extends from the first element to the specified index.

public:
 int FindLastIndex(int startIndex, Predicate<T> ^ match);
public int FindLastIndex (int startIndex, Predicate<T> match);
member this.FindLastIndex : int * Predicate<'T> -> int
Public Function FindLastIndex (startIndex As Integer, match As Predicate(Of T)) As Integer

パラメーター

startIndex
Int32

後方検索の開始位置を示す 0 から始まるインデックス。The zero-based starting index of the backward search.

match
Predicate<T>

検索する要素の条件を定義する Predicate<T> デリゲート。The Predicate<T> delegate that defines the conditions of the element to search for.

戻り値

match で定義された条件と一致する要素が存在する場合、最もインデックス番号の大きい要素の 0 から始まるインデックス。それ以外の場合は -1。The zero-based index of the last occurrence of an element that matches the conditions defined by match, if found; otherwise, -1.

例外

matchnullです。match is null.

startIndexList<T> の有効なインデックスの範囲外です。startIndex is outside the range of valid indexes for the List<T>.

注釈

List<T>startIndex から後方に検索され、最初の要素で終了します。The List<T> is searched backward starting at startIndex and ending at the first element.

Predicate<T> は、渡されたオブジェクトがデリゲートで定義されている条件に一致する場合に true を返すメソッドのデリゲートです。The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. 現在の List<T> の要素は、Predicate<T> デリゲートに個別に渡されます。The elements of the current List<T> are individually passed to the Predicate<T> delegate.

このメソッドは、線形検索を実行します。したがって、このメソッドは O (n) 演算です。ここで、 nは、startIndexする List<T> の先頭からの要素の数です。This method performs a linear search; therefore, this method is an O(n) operation, where n is the number of elements from the beginning of the List<T> to startIndex.

こちらもご覧ください

FindLastIndex(Int32, Int32, Predicate<T>)

List<T> のうち、指定したインデックスで終わり、指定した要素数が含まれる範囲の中で、指定した述語によって定義される条件に一致する要素を検索し、そのうち最もインデックス番号の大きい要素の 0 から始まるインデックスを返します。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List<T> that contains the specified number of elements and ends at the specified index.

public:
 int FindLastIndex(int startIndex, int count, Predicate<T> ^ match);
public int FindLastIndex (int startIndex, int count, Predicate<T> match);
member this.FindLastIndex : int * int * Predicate<'T> -> int
Public Function FindLastIndex (startIndex As Integer, count As Integer, match As Predicate(Of T)) As Integer

パラメーター

startIndex
Int32

後方検索の開始位置を示す 0 から始まるインデックス。The zero-based starting index of the backward search.

count
Int32

検索対象の範囲内にある要素の数。The number of elements in the section to search.

match
Predicate<T>

検索する要素の条件を定義する Predicate<T> デリゲート。The Predicate<T> delegate that defines the conditions of the element to search for.

戻り値

match で定義された条件と一致する要素が存在する場合、最もインデックス番号の大きい要素の 0 から始まるインデックス。それ以外の場合は -1。The zero-based index of the last occurrence of an element that matches the conditions defined by match, if found; otherwise, -1.

例外

matchnull です。match is null.

startIndexList<T> の有効なインデックスの範囲外です。startIndex is outside the range of valid indexes for the List<T>.

- または --or- count が 0 未満です。count is less than 0.

- または --or- startIndex および countList<T> 内の正しいセクションを指定していません。startIndex and count do not specify a valid section in the List<T>.

次の例は、List<T> クラスの find メソッドを示しています。The following example demonstrates the find methods for the List<T> class. List<T> クラスの例には、サンプル XML ファイルのデータを使用して、クラス Bookbook オブジェクトが含まれています。書籍 (LINQ to XML)」。The example for the List<T> class contains book objects, of class Book, using the data from the Sample XML File: Books (LINQ to XML). この例の FillList メソッドでは、 LINQ to XMLを使用して、XML から book オブジェクトのプロパティ値を解析します。The FillList method in the example uses LINQ to XML to parse the values from the XML to property values of the book objects.

次の表では、find メソッドに用意されている例について説明します。The following table describes the examples provided for the find methods.

メソッドMethod Example
Find(Predicate<T>) IDToFind 述語デリゲートを使用して、ID で書籍を検索します。Finds a book by an ID using the IDToFind predicate delegate.

C#例では、匿名デリゲートを使用します。C# example uses an anonymous delegate.
FindAll(Predicate<T>) FindComputer 述語デリゲートを使用して、Genre プロパティが "Computer" であるすべての書籍を検索します。Find all books that whose Genre property is "Computer" using the FindComputer predicate delegate.
FindLast(Predicate<T>) PubBefore2001 述語デリゲートを使用して、2001より前の発行日を持つ、コレクション内の最後のブックを検索します。Finds the last book in the collection that has a publish date before 2001, using the PubBefore2001 predicate delegate.

C#例では、匿名デリゲートを使用します。C# example uses an anonymous delegate.
FindIndex(Predicate<T>) FindComputer 述語デリゲートを使用して、最初のコンピューターブックのインデックスを検索します。Finds the index of first computer book using the FindComputer predicate delegate.
FindLastIndex(Predicate<T>) FindComputer 述語デリゲートを使用して、最後のコンピューターブックのインデックスを検索します。Finds the index of the last computer book using the FindComputer predicate delegate.
FindIndex(Int32, Int32, Predicate<T>) FindComputer 述語デリゲートを使用して、コレクションの後半にある最初のコンピューターブックのインデックスを検索します。Finds the index of first computer book in the second half of the collection, using the FindComputer predicate delegate.
FindLastIndex(Int32, Int32, Predicate<T>) FindComputer 述語デリゲートを使用して、コレクションの後半で最後のコンピューターブックのインデックスを検索します。Finds the index of last computer book in the second half of the collection, using the FindComputer predicate delegate.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Find
{
    class Program
    {
        private static string IDtoFind = "bk109";

        private static List<Book> Books = new List<Book>();
        public static void Main(string[] args)
        {
            FillList();
            
            // Find a book by its ID.
            Book result = Books.Find(
            delegate(Book bk)
            {
                return bk.ID == IDtoFind;
            }
            );
            if (result != null)
            {
                DisplayResult(result, "Find by ID: " + IDtoFind);   
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }


            // Find last book in collection published before 2001.
            result = Books.FindLast(
            delegate(Book bk)
            {
                DateTime year2001 = new DateTime(2001,01,01);
                return bk.Publish_date < year2001;
            });
            if (result != null)
            {
                DisplayResult(result, "Last book in collection published before 2001:");
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }


            // Find all computer books.
            List<Book> results = Books.FindAll(FindComputer);
            if (results.Count != 0)
            {
                DisplayResults(results, "All computer:");
            }
            else
            {
                Console.WriteLine("\nNo books found.");
            }

            // Find all books under $10.00.
            results = Books.FindAll(
            delegate(Book bk)
            {
                return bk.Price < 10.00;
            }
            );
            if (results.Count != 0)
            {
                DisplayResults(results, "Books under $10:");
            }
            else
            {
                Console.WriteLine("\nNo books found.");
            }
            

            // Find index values.
            Console.WriteLine();
            int ndx = Books.FindIndex(FindComputer);
            Console.WriteLine("Index of first computer book: {0}", ndx);
            ndx = Books.FindLastIndex(FindComputer);
            Console.WriteLine("Index of last computer book: {0}", ndx);

            int mid = Books.Count / 2;
            ndx = Books.FindIndex(mid, mid, FindComputer);
            Console.WriteLine("Index of first computer book in the second half of the collection: {0}", ndx);
            
            ndx = Books.FindLastIndex(Books.Count - 1, mid, FindComputer);
            Console.WriteLine("Index of last computer book in the second half of the collection: {0}", ndx);

        }





        // Populates the list with sample data.
        private static void FillList()
        {
            
            // Create XML elements from a source file.
            XElement xTree = XElement.Load(@"c:\temp\books.xml");

            // Create an enumerable collection of the elements.
            IEnumerable<XElement> elements = xTree.Elements();

            // Evaluate each element and set set values in the book object.
            foreach (XElement el in elements)
            {
                Book book = new Book();
                book.ID = el.Attribute("id").Value;
                IEnumerable<XElement> props = el.Elements();
                foreach (XElement p in props)
                {


                    if (p.Name.ToString().ToLower() == "author")
                    {
                        book.Author = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "title")
                    {
                        book.Title = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "genre")
                    {
                        book.Genre = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "price")
                    {
                        book.Price = Convert.ToDouble(p.Value);
                    }
                    else if (p.Name.ToString().ToLower() == "publish_date")
                    {
                        book.Publish_date = Convert.ToDateTime(p.Value);
                    }
                    else if (p.Name.ToString().ToLower() == "description")
                    {
                        book.Description = p.Value;
                    }
                }

                Books.Add(book);

            }

            DisplayResults(Books, "All books:");

        }

        // Explicit predicate delegate.
        private static bool FindComputer(Book bk)
        {

            if (bk.Genre == "Computer")
            {
                return true;
            }
        else
            {
                return false;
            }

        }

        private static void DisplayResult(Book result, string title)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", result.ID,
                result.Author, result.Title, result.Genre, result.Price,
                result.Publish_date.ToShortDateString());
            Console.WriteLine();


        }

        private static void DisplayResults(List<Book> results, string title)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            foreach (Book b in results)
            {

                Console.Write("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", b.ID,
                    b.Author, b.Title, b.Genre, b.Price,
                    b.Publish_date.ToShortDateString());
            }
            Console.WriteLine();

        }

    }

    public class Book
    {
        public string ID { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
        public string Genre { get; set; }
        public double Price { get; set; }
        public DateTime Publish_date { get; set; }
        public string Description { get; set; }
    }
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Module Module1

    Private IDToFind As String = "bk109"

    Public Books As New List(Of Book)


    Sub Main()

        FillList()

        ' Find a book by its ID.
        Dim result As Book = Books.Find(AddressOf FindID)
        If result IsNot Nothing Then
            DisplayResult(result, "Find by ID: " & IDToFind)
        Else

            Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
        End If
        Console.WriteLine()

        ' Find last book in collection that has a publish date before 2001.
        result = Books.FindLast(AddressOf PubBefore2001)
        If result IsNot Nothing Then
            DisplayResult(result, "Last book in collection published before 2001:")
        Else
            Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
        End If
        Console.WriteLine()

        ' Find all computer books.
        Dim results As List(Of Book) = Books.FindAll(AddressOf FindComputer)
        If results.Count <> 0 Then
            DisplayResults(results, "All computer books:")
        Else
            Console.WriteLine(vbCrLf & "No books found.")
        End If
        Console.WriteLine()


        ' Find all books under $10.00.
        results = Books.FindAll(AddressOf FindUnderTen)
        If results.Count <> 0 Then
            DisplayResults(results, "Books under $10:")
        Else
            Console.WriteLine(vbCrLf & "No books found.")
        End If
        Console.WriteLine()

        ' Find index values.
        Console.WriteLine()
        Dim ndx As Integer = Books.FindIndex(AddressOf FindComputer)
        Console.WriteLine("Index of first computer book: " & ndx)
        ndx = Books.FindLastIndex(AddressOf FindComputer)
        Console.WriteLine("Index of last computer book: " & ndx)

        Dim mid As Integer = Books.Count / 2
        ndx = Books.FindIndex(mid, mid, AddressOf FindComputer)
        Console.WriteLine("Index of first computer book in the second half of the collection: " & ndx)



        ndx = Books.FindLastIndex(Books.Count - 1, mid, AddressOf FindComputer)
        Console.WriteLine("Index of last computer book in the second half of the collection: " & ndx)


    End Sub



    Private Sub FillList()

        ' Create XML elements from a source file.
        Dim xTree As XElement = XElement.Load("c:\temp\books.xml")

        ' Create an enumerable collection of the elements.
        Dim elements As IEnumerable(Of XElement) = xTree.Elements

        ' Evaluate each element and set values in the book object.
        For Each el As XElement In elements
            Dim Book As New Book()
            Book.ID = el.Attribute("id").Value
            Dim props As IEnumerable(Of XElement) = el.Elements
            For Each p As XElement In props
                If p.Name.ToString.ToLower = "author" Then
                    Book.Author = p.Value
                End If
                If p.Name.ToString.ToLower = "title" Then
                    Book.Title = p.Value
                End If
                If p.Name.ToString.ToLower = "genre" Then
                    Book.Genre = p.Value
                End If
                If p.Name.ToString.ToLower = "price" Then
                    Book.Price = Convert.ToDouble(p.Value)
                End If
                If p.Name.ToString.ToLower = "publish_date" Then
                    Book.Publish_date = Convert.ToDateTime(p.Value)
                End If
                If p.Name.ToString.ToLower = "description" Then
                    Book.Description = p.Value
                End If
            Next
            Books.Add(Book)
        Next

        DisplayResults(Books, "All books:")
        Console.WriteLine()

    End Sub

    ' Predicate delegates for
    ' Find and FindAll methods.
    Private Function FindID(ByVal bk As Book) As Boolean
        If bk.ID = IDToFind Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function FindComputer(ByVal bk As Book) As Boolean
        If bk.Genre = "Computer" Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function FindUnderTen(ByVal bk As Book) As Boolean
        Dim tendollars As Double = 10.0
        If bk.Price < tendollars Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function PubBefore2001(ByVal bk As Book) As Boolean
        Dim year2001 As DateTime = New DateTime(2001, 1, 1)
        Return bk.Publish_date < year2001
    End Function
    Private Sub DisplayResult(ByVal result As Book, ByVal title As String)
        Console.WriteLine()
        Console.WriteLine(title)
        Console.WriteLine(vbLf & result.ID & vbTab & result.Author & _
                          vbTab & result.Title & vbTab & result.Genre & _
                          vbTab & result.Publish_date & vbTab & result.Price)
        Console.WriteLine()
    End Sub
    Private Sub DisplayResults(ByVal results As List(Of Book), ByVal title As String)
        Console.WriteLine()
        Console.WriteLine(title)
        For Each b As Book In results
            Console.Write(vbLf & b.ID & vbTab & b.Author & _
                              vbTab & b.Title & vbTab & b.Genre & _
                              vbTab & b.Publish_date & vbTab & b.Price)
        Next
        Console.WriteLine()
    End Sub

    Public Class Book
        Public ID As String
        Public Author As String
        Public Title As String
        Public Genre As String
        Public Price As Double
        Public Publish_date As DateTime
        Public Description As String
    End Class


End Module

注釈

List<T> は、startIndex から後方に検索され、count が0よりも大きい場合は startIndex からマイナス count になります。The List<T> is searched backward starting at startIndex and ending at startIndex minus count plus 1, if count is greater than 0.

Predicate<T> は、渡されたオブジェクトがデリゲートで定義されている条件に一致する場合に true を返すメソッドのデリゲートです。The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. 現在の List<T> の要素は、Predicate<T> デリゲートに個別に渡されます。The elements of the current List<T> are individually passed to the Predicate<T> delegate.

このメソッドは、線形検索を実行します。したがって、このメソッドは O (n) 操作です。ここで、 ncountです。This method performs a linear search; therefore, this method is an O(n) operation, where n is count.

こちらもご覧ください

適用対象