Array.FindLast(T[], Predicate<T>) Array.FindLast(T[], Predicate<T>) Array.FindLast(T[], Predicate<T>) Array.FindLast(T[], Predicate<T>) Method

정의

지정된 조건자에 정의된 조건과 일치하는 요소를 검색하고 전체 Array에서 마지막으로 검색한 요소를 반환합니다.Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire Array.

public:
generic <typename T>
 static T FindLast(cli::array <T> ^ array, Predicate<T> ^ match);
public static T FindLast<T> (T[] array, Predicate<T> match);
static member FindLast : 'T[] * Predicate<'T> -> 'T
Public Shared Function FindLast(Of T) (array As T(), match As Predicate(Of T)) As T

형식 매개 변수

T

배열 요소의 형식입니다.The type of the elements of the array.

매개 변수

array
T[]

검색할 1차원 Array(인덱스는 0부터 시작)입니다.The one-dimensional, zero-based Array to search.

match
Predicate<T> Predicate<T> Predicate<T> Predicate<T>

검색할 요소의 조건을 정의하는 Predicate<T>입니다.The Predicate<T> that defines the conditions of the element to search for.

반환

T T T T

지정된 조건자에 정의된 조건과 일치하는 요소가 있으면 일치하는 요소 중 마지막 요소이고, 그렇지 않으면 T 형식의 기본값입니다.The last element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.

예외

arraynull인 경우array is null.

또는-or- matchnull입니다.match is null.

예제

다음 코드 예제는 Find, FindLast, 및 FindAll 제네릭 메서드.The following code example demonstrates the Find, FindLast, and FindAll generic methods. "Saurus"를 사용 하 여 종료 (위치 1과 5)는 두 개의 8 공룡 이름이 포함 된 문자열 배열을 만들어집니다.An array of strings is created, containing 8 dinosaur names, two of which (at positions 1 and 5) end with "saurus". 코드 예제에서는 명명 된 검색 조건자 메서드도 정의 EndsWithSaurus문자열 매개 변수를 수락 하 고 부울 값을 반환 나타내는 "saurus"로 입력된 문자열 종료 여부를 합니다.The code example also defines a search predicate method named EndsWithSaurus, which accepts a string parameter and returns a Boolean value indicating whether the input string ends in "saurus".

합니다 Find 제네릭 메서드를 차례로 각 요소를 전달부터 배열을 트래버스하는 EndsWithSaurus 메서드.The Find generic method traverses the array from the beginning, passing each element in turn to the EndsWithSaurus method. 검색을 중지 하는 경우는 EndsWithSaurus 메서드가 반환 되는 true "Amargasaurus" 요소에 대 한 합니다.The search stops when the EndsWithSaurus method returns true for the element "Amargasaurus".

참고

C# 및 Visual Basic에서는 필요 없는 만들려면 합니다Predicate<string> 대리자 (Predicate(Of String) Visual Basic의) 명시적으로 합니다.In C# and Visual Basic, it is not necessary to create thePredicate<string> delegate (Predicate(Of String) in Visual Basic) explicitly. 이러한 언어는 상황에 맞는 올바른 대리자 유추 하 고 자동으로 만듭니다.These languages infer the correct delegate from context and create it automatically.

FindLast 제네릭 메서드는 배열의 끝에서 뒤로 검색 합니다 하는 데 사용 됩니다.The FindLast generic method is used to search the array backward from the end. 위치 5에서 "Dilophosaurus를" 요소를 찾습니다.It finds the element "Dilophosaurus" at position 5. FindAll 제네릭 메서드는 "saurus"로 끝나는 모든 요소가 포함 된 배열을 반환 하는 데 사용 됩니다.The FindAll generic method is used to return an array containing all the elements that end in "saurus". 요소가 표시 됩니다.The elements are displayed.

코드 예제도 합니다 ExistsTrueForAll 제네릭 메서드.The code example also demonstrates the Exists and TrueForAll generic methods.

using namespace System;

public ref class DinoDiscoverySet
{
public:
    static void Main()
    {
        array<String^>^ dinosaurs =
        {
            "Compsognathus", "Amargasaurus", "Oviraptor",
            "Velociraptor",  "Deinonychus",  "Dilophosaurus",
            "Gallimimus",    "Triceratops"
        };

        DinoDiscoverySet^ GoMesozoic = gcnew DinoDiscoverySet(dinosaurs);

        GoMesozoic->DiscoverAll();
        GoMesozoic->DiscoverByEnding("saurus");
    }

    DinoDiscoverySet(array<String^>^ items)
    {
        dinosaurs = items;
    }

    void DiscoverAll()
    {
        Console::WriteLine();
        for each(String^ dinosaur in dinosaurs)
        {
            Console::WriteLine(dinosaur);
        }
    }

    void DiscoverByEnding(String^ Ending)
    {
        Predicate<String^>^ dinoType;

        if (Ending->ToLower() == "raptor")
        {
            dinoType =
                gcnew Predicate<String^>(&DinoDiscoverySet::EndsWithRaptor);
        }
        else if (Ending->ToLower() == "tops")
        {
            dinoType =
                gcnew Predicate<String^>(&DinoDiscoverySet::EndsWithTops);
        }
        else if (Ending->ToLower() == "saurus")
        {
            dinoType =
                gcnew Predicate<String^>(&DinoDiscoverySet::EndsWithSaurus);
        }
        else
        {
            dinoType =
                gcnew Predicate<String^>(&DinoDiscoverySet::EndsWithSaurus);
        }

        Console::WriteLine(
            "\nArray::Exists(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array::Exists(dinosaurs, dinoType));

        Console::WriteLine(
            "\nArray::TrueForAll(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array::TrueForAll(dinosaurs, dinoType));

        Console::WriteLine(
            "\nArray::Find(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array::Find(dinosaurs, dinoType));

        Console::WriteLine(
            "\nArray::FindLast(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array::FindLast(dinosaurs, dinoType));

        Console::WriteLine(
            "\nArray::FindAll(dinosaurs, \"{0}\"):", Ending);

        array<String^>^ subArray =
            Array::FindAll(dinosaurs, dinoType);

        for each(String^ dinosaur in subArray)
        {
            Console::WriteLine(dinosaur);
        }
    }

private:
    array<String^>^ dinosaurs;

    // Search predicate returns true if a string ends in "saurus".
    static bool EndsWithSaurus(String^ s)
    {
        if ((s->Length > 5) &&
            (s->Substring(s->Length - 6)->ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // Search predicate returns true if a string ends in "raptor".
    static bool EndsWithRaptor(String^ s)
    {
        if ((s->Length > 5) &&
            (s->Substring(s->Length - 6)->ToLower() == "raptor"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // Search predicate returns true if a string ends in "tops".
    static bool EndsWithTops(String^ s)
    {
        if ((s->Length > 3) &&
            (s->Substring(s->Length - 4)->ToLower() == "tops"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

int main()
{
    DinoDiscoverySet::Main();
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

Array.Exists(dinosaurs, "saurus"): True

Array.TrueForAll(dinosaurs, "saurus"): False

Array.Find(dinosaurs, "saurus"): Amargasaurus

Array.FindLast(dinosaurs, "saurus"): Dilophosaurus

Array.FindAll(dinosaurs, "saurus"):
Amargasaurus
Dilophosaurus
*/
using System;

public class DinoDiscoverySet
{
    public static void Main()
    {
        string[] dinosaurs =
        {
            "Compsognathus", "Amargasaurus", "Oviraptor",
            "Velociraptor",  "Deinonychus",  "Dilophosaurus",
            "Gallimimus",    "Triceratops"
        };

        DinoDiscoverySet GoMesozoic = new DinoDiscoverySet(dinosaurs);
        
        GoMesozoic.DiscoverAll();
        GoMesozoic.DiscoverByEnding("saurus");
    }

    private string[] dinosaurs;

    public DinoDiscoverySet(string[] items)
    {
        dinosaurs = items;
    }

    public void DiscoverAll()
    {
        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
    }

    public void DiscoverByEnding(string Ending)
    {
        Predicate<string> dinoType;

        switch (Ending.ToLower())
        {
            case "raptor":
                dinoType = EndsWithRaptor;
                break;
            case "tops":
                dinoType = EndsWithTops;
                break;
            case "saurus":
            default:
                dinoType = EndsWithSaurus;
                break;
        }
        Console.WriteLine(
            "\nArray.Exists(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array.Exists(dinosaurs, dinoType));

        Console.WriteLine(
            "\nArray.TrueForAll(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array.TrueForAll(dinosaurs, dinoType));

        Console.WriteLine(
            "\nArray.Find(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array.Find(dinosaurs, dinoType));

        Console.WriteLine(
            "\nArray.FindLast(dinosaurs, \"{0}\"): {1}",
            Ending,
            Array.FindLast(dinosaurs, dinoType));

        Console.WriteLine(
            "\nArray.FindAll(dinosaurs, \"{0}\"):", Ending);

        string[] subArray =
            Array.FindAll(dinosaurs, dinoType);

        foreach(string dinosaur in subArray)
        {
            Console.WriteLine(dinosaur);
        }
    }

    // Search predicate returns true if a string ends in "saurus".
    private bool EndsWithSaurus(string s)
    {
        if ((s.Length > 5) &&
            (s.Substring(s.Length - 6).ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // Search predicate returns true if a string ends in "raptor".
    private bool EndsWithRaptor(String s)
    {
        if ((s.Length > 5) &&
            (s.Substring(s.Length - 6).ToLower() == "raptor"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // Search predicate returns true if a string ends in "tops".
    private bool EndsWithTops(String s)
    {
        if ((s.Length > 3) &&
            (s.Substring(s.Length - 4).ToLower() == "tops"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

Array.Exists(dinosaurs, "saurus"): True

Array.TrueForAll(dinosaurs, "saurus"): False

Array.Find(dinosaurs, "saurus"): Amargasaurus

Array.FindLast(dinosaurs, "saurus"): Dilophosaurus

Array.FindAll(dinosaurs, "saurus"):
Amargasaurus
Dilophosaurus
*/
Public Class DinoDiscoverySet

    Public Shared Sub Main()
        Dim dinosaurs() As String = { "Compsognathus", _
            "Amargasaurus",   "Oviraptor",      "Velociraptor", _
            "Deinonychus",    "Dilophosaurus",  "Gallimimus", _
            "Triceratops" }

        Dim GoMesozoic As New DinoDiscoverySet(dinosaurs)

        GoMesozoic.DiscoverAll()
        GoMesozoic.DiscoverByEnding("saurus")
    End Sub

    Private dinosaurs As String()

    Public Sub New(items() As String)
        dinosaurs = items
    End Sub

    Public Sub DiscoverAll()
        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next dinosaur
    End Sub

    Public Sub DiscoverByEnding(Ending As String)
        Dim dinoType As Predicate(Of String)

        Select Case Ending.ToLower()
            Case "raptor"
                dinoType = AddressOf EndsWithRaptor
            Case "tops"
                dinoType = AddressOf EndsWithTops
            Case "saurus"
                dinoType = AddressOf EndsWithSaurus
            Case Else
                dinoType = AddressOf EndsWithSaurus
        End Select

        Console.WriteLine(vbNewLine + _
            "Array.Exists(dinosaurs, ""{0}""): {1}", _
            Ending, _
            Array.Exists(dinosaurs, dinoType))

        Console.WriteLine(vbNewLine + _
            "Array.TrueForAll(dinosaurs, ""{0}""): {1}", _
            Ending, _
            Array.TrueForAll(dinosaurs, dinoType))

        Console.WriteLine(vbNewLine + _
            "Array.Find(dinosaurs, ""{0}""): {1}", _
            Ending, _
            Array.Find(dinosaurs, dinoType))

        Console.WriteLine(vbNewLine + _
            "Array.FindLast(dinosaurs, ""{0}""): {1}", _
            Ending, _
            Array.FindLast(dinosaurs, dinoType))

        Console.WriteLine(vbNewLine + _
            "Array.FindAll(dinosaurs, ""{0}""):", Ending)

        Dim subArray() As String = _
            Array.FindAll(dinosaurs, dinoType)

        For Each dinosaur As String In subArray
            Console.WriteLine(dinosaur)
        Next dinosaur
    End Sub

    ' Search predicate returns true if a string ends in "saurus".
    Private Function EndsWithSaurus(s As String) As Boolean
        ' AndAlso prevents evaluation of the second Boolean
        ' expression if the string is so short that an error
        ' would occur.
        If (s.Length > 5) AndAlso _
            (s.ToLower().EndsWith("saurus")) Then
            Return True
        Else
            Return False
        End If
    End Function

    ' Search predicate returns true if a string ends in "raptor".
    Private Function EndsWithRaptor(s As String) As Boolean
        ' AndAlso prevents evaluation of the second Boolean
        ' expression if the string is so short that an error
        ' would occur.
        If (s.Length > 5) AndAlso _
            (s.ToLower().EndsWith("raptor")) Then
            Return True
        Else
            Return False
        End If
    End Function

    ' Search predicate returns true if a string ends in "tops".
    Private Function EndsWithTops(s As String) As Boolean
        ' AndAlso prevents evaluation of the second Boolean
        ' expression if the string is so short that an error
        ' would occur.
        If (s.Length > 3) AndAlso _
            (s.ToLower().EndsWith("tops")) Then
            Return True
        Else
            Return False
        End If
    End Function
End Class

' This code example produces the following output:
'
' Compsognathus
' Amargasaurus
' Oviraptor
' Velociraptor
' Deinonychus
' Dilophosaurus
' Gallimimus
' Triceratops
'
' Array.Exists(dinosaurs, "saurus"): True
'
' Array.TrueForAll(dinosaurs, "saurus"): False
'
' Array.Find(dinosaurs, "saurus"): Amargasaurus
'
' Array.FindLast(dinosaurs, "saurus"): Dilophosaurus
'
' Array.FindAll(dinosaurs, "saurus"):
' Amargasaurus
' Dilophosaurus

설명

합니다 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. 요소의 array 에 개별적으로 전달 되는 Predicate<T>이동에서 이전 버전과는 Array, 마지막 요소를 사용 하 여 시작 하 고 첫 번째 요소를 사용 하 여 종료 합니다.The elements of array are individually passed to the Predicate<T>, moving backward in the Array, starting with the last element and ending with the first element. 일치 하는 경우 처리가 중지 됩니다.Processing is stopped when a match is found.

이 메서드는 O (n) 작업을 여기서 nLengtharray합니다.This method is an O(n) operation, where n is the Length of array.

적용 대상

추가 정보