List<T>.FindLastIndex 메서드

정의

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하고 List<T>이나 그 일부에서 마지막으로 검색한 요소의 인덱스(0부터 시작)를 반환합니다.

오버로드

FindLastIndex(Predicate<T>)

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 전체 List<T>에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다.

FindLastIndex(Int32, Predicate<T>)

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 첫 번째 요소에서 지정된 인덱스로 확장하는 List<T>의 요소 범위에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다.

FindLastIndex(Int32, Int32, Predicate<T>)

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 지정된 수의 요소가 들어 있고 지정된 인덱스에서 끝나는 List<T> 의 요소 범위에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다.

FindLastIndex(Predicate<T>)

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 전체 List<T>에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다.

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> 대리자입니다.

반환

match에 정의된 조건과 일치하는 요소가 있으면 그 중 마지막 요소의 인덱스(0부터 시작)이고, 그렇지 않으면 -1입니다.

예외

match이(가) null인 경우

예제

다음 예제에서는 클래스의 찾기 메서드를 보여 줍니다 List<T> . 클래스의 List<T> 예제에는 샘플 XML 파일: Books(LINQ to XML)의 데이터를 사용하여 클래스Book의 개체가 포함되어 book 있습니다. 예제의 메서드는 FillListLINQ to XML 사용하여 XML의 값을 개체의 book 속성 값으로 구문 분석합니다.

다음 표에서는 찾기 메서드에 제공된 예제를 설명합니다.

방법 예제
Find(Predicate<T>) 조건자 대리자를 사용하여 ID로 IDToFind 책을 찾습니다.

C# 예제에서는 익명 대리자를 사용합니다.
FindAll(Predicate<T>) 조건자 대리자를 사용하여 FindComputer 속성이 Genre "컴퓨터"인 모든 책을 찾습니다.
FindLast(Predicate<T>) 조건자 대리자를 사용하여 2001년 이전의 게시 날짜가 있는 컬렉션의 PubBefore2001 마지막 책을 찾습니다.

C# 예제에서는 익명 대리자를 사용합니다.
FindIndex(Predicate<T>) 조건자 대리자를 사용하여 첫 번째 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
FindLastIndex(Predicate<T>) 조건자 대리자를 사용하여 마지막 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
FindIndex(Int32, Int32, Predicate<T>) 조건자 대리자를 사용하여 컬렉션의 후반부에 있는 첫 번째 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
FindLastIndex(Int32, Int32, Predicate<T>) 조건자 대리자를 사용하여 컬렉션의 후반부에 있는 마지막 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
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> 마지막 요소에서 시작하여 첫 번째 요소에서 끝나는 뒤로 검색됩니다.

Predicate<T> 전달된 개체가 대리자에서 정의된 조건과 일치하는 경우 를 반환 true 하는 메서드에 대한 대리자입니다. 현재 List<T> 의 요소는 개별적으로 대리자에게 Predicate<T> 전달됩니다.

이 메서드는 선형 검색을 수행합니다. 따라서 이 메서드는 O(n) 작업이며 여기서 n 은 입니다 Count.

추가 정보

적용 대상

FindLastIndex(Int32, Predicate<T>)

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 첫 번째 요소에서 지정된 인덱스로 확장하는 List<T>의 요소 범위에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다.

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부터 시작하는 인덱스입니다.

match
Predicate<T>

검색할 요소의 조건을 정의하는 Predicate<T> 대리자입니다.

반환

match에 정의된 조건과 일치하는 요소가 있으면 그 중 마지막 요소의 인덱스(0부터 시작)이고, 그렇지 않으면 -1입니다.

예외

match이(가) null인 경우

startIndexList<T>의 유효한 인덱스 범위를 벗어납니다.

설명

List<T> 에서 시작하여 첫 번째 요소에서 startIndex 끝나는 뒤로 검색됩니다.

Predicate<T> 전달된 개체가 대리자에서 정의된 조건과 일치하는 경우 를 반환 true 하는 메서드에 대한 대리자입니다. 현재 List<T> 의 요소는 개별적으로 대리자에게 Predicate<T> 전달됩니다.

이 메서드는 선형 검색을 수행합니다. 따라서 이 메서드는 O(n) 연산입니다. 여기서 n 은 의 시작 부분에서 로의 List<T>startIndex요소 수입니다.

추가 정보

적용 대상

FindLastIndex(Int32, Int32, Predicate<T>)

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 지정된 수의 요소가 들어 있고 지정된 인덱스에서 끝나는 List<T> 의 요소 범위에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다.

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부터 시작하는 인덱스입니다.

count
Int32

검색할 섹션에 있는 요소 수입니다.

match
Predicate<T>

검색할 요소의 조건을 정의하는 Predicate<T> 대리자입니다.

반환

match에 정의된 조건과 일치하는 요소가 있으면 그 중 마지막 요소의 인덱스(0부터 시작)이고, 그렇지 않으면 -1입니다.

예외

match이(가) null인 경우

startIndexList<T>의 유효한 인덱스 범위를 벗어납니다.

또는

count 가 0보다 작습니다.

또는

startIndexcountList<T>의 올바른 섹션을 지정하지 않습니다.

예제

다음 예제에서는 클래스의 찾기 메서드를 보여 줍니다 List<T> . 클래스의 List<T> 예제에는 샘플 XML 파일: Books(LINQ to XML)의 데이터를 사용하여 클래스Book의 개체가 포함되어 book 있습니다. 예제의 메서드는 FillListLINQ to XML 사용하여 XML의 값을 개체의 book 속성 값으로 구문 분석합니다.

다음 표에서는 찾기 메서드에 제공된 예제를 설명합니다.

방법 예제
Find(Predicate<T>) 조건자 대리자를 사용하여 ID로 IDToFind 책을 찾습니다.

C# 예제에서는 익명 대리자를 사용합니다.
FindAll(Predicate<T>) 조건자 대리자를 사용하여 FindComputer 속성이 Genre "컴퓨터"인 모든 책을 찾습니다.
FindLast(Predicate<T>) 조건자 대리자를 사용하여 2001년 이전의 게시 날짜가 있는 컬렉션의 PubBefore2001 마지막 책을 찾습니다.

C# 예제에서는 익명 대리자를 사용합니다.
FindIndex(Predicate<T>) 조건자 대리자를 사용하여 첫 번째 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
FindLastIndex(Predicate<T>) 조건자 대리자를 사용하여 마지막 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
FindIndex(Int32, Int32, Predicate<T>) 조건자 대리자를 사용하여 컬렉션의 후반부에 있는 첫 번째 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
FindLastIndex(Int32, Int32, Predicate<T>) 조건자 대리자를 사용하여 컬렉션의 후반부에 있는 마지막 컴퓨터 책의 인덱스 FindComputer 를 찾습니다.
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> 0보다 큰 경우 count 는 에서 startIndex 시작하여 빼기 count 및 1에서 끝나는 startIndex 뒤로 검색됩니다.

Predicate<T> 전달된 개체가 대리자에서 정의된 조건과 일치하는 경우 를 반환 true 하는 메서드에 대한 대리자입니다. 현재 List<T> 의 요소는 개별적으로 대리자에게 Predicate<T> 전달됩니다.

이 메서드는 선형 검색을 수행합니다. 따라서 이 메서드는 O(n) 작업이며 여기서 n 은 입니다 count.

추가 정보

적용 대상