Array.FindAll<T>(T[], Predicate<T>) 메서드

정의

지정한 조건자에 정의된 조건과 일치하는 모든 요소를 검색합니다.

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

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

검색할 1차원 Array(인덱스는 0부터 시작)입니다.

match
Predicate<T>

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

반환

T[]

지정된 조건자에 정의된 조건과 일치하는 요소가 있으면 해당 요소를 모두 포함하는 Array 이고, 그렇지 않으면 빈 Array입니다.

예외

array이(가) null인 경우

또는

match이(가) null인 경우

예제

다음 예제에서는 0에서 1,000까지의 값으로 50개의 난수 배열을 만듭니다. 그런 다음 300에서 600까지의 값을 반환하는 람다 식을 사용하여 메서드를 호출 FindAll 합니다. 람다 식은 ;라는 x매개 변수를 전달합니다. 에 전달되는 개별 배열 멤버를 Predicate<T>나타냅니다. 또한 람다 식 내에서 로컬 lBounduBound 변수에 액세스할 수 있습니다.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      // Get an array of n random integers.
      int[] values = GetArray(50, 0, 1000);
      int lBound = 300;
      int uBound = 600;
      int[] matchedItems = Array.FindAll(values, x =>
                                       x >= lBound && x <= uBound);
      for (int ctr = 0; ctr < matchedItems.Length; ctr++) {
         Console.Write("{0}  ", matchedItems[ctr]);
         if ((ctr + 1) % 12 == 0)
            Console.WriteLine();
      }
   }

   private static int[] GetArray(int n, int lower, int upper)
   {
      Random rnd = new Random();
      List<int> list = new List<int>();
      for (int ctr = 1; ctr <= n; ctr++)
         list.Add(rnd.Next(lower, upper + 1));

      return list.ToArray();
   }
}
// The example displays output similar to the following:
//       542  398  356  351  348  301  562  599  575  400  569  306
//       535  416  393  385
open System

let getArray n lower upper =
    let rnd = Random()
    [|  for _ = 1 to n do 
            rnd.Next(lower, upper + 1) |]

// Get an array of n random integers.
let values = getArray 50 0 1000
let lBound = 300
let uBound = 600
let matchedItems = Array.FindAll(values, fun x -> x >= lBound && x <= uBound)

for i = 0 to matchedItems.Length - 1 do
    printf $"{matchedItems[i]}  "
    if (i + 1) % 12 = 0 then printfn ""

// The example displays output similar to the following:
//       542  398  356  351  348  301  562  599  575  400  569  306
//       535  416  393  385
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      ' Get an array of n random integers.
      Dim values() As Integer = GetArray(50, 0, 1000)
      Dim lBound As Integer = 300
      Dim uBound As Integer = 600
      Dim matchedItems() As Integer = Array.FindAll(values, 
                                            Function(x) x >= lBound And x <= uBound)  
      For ctr As Integer = 0 To matchedItems.Length - 1
         Console.Write("{0}  ", matchedItems(ctr))
         If (ctr + 1) Mod 12 = 0 Then Console.WriteLine()
      Next
   End Sub
   
   Private Function GetArray(n As Integer, lower As Integer, 
                             upper As Integer) As Integer()
      Dim rnd As New Random()
      Dim list As New List(Of Integer)
      For ctr As Integer = 1 To n
         list.Add(rnd.Next(lower, upper + 1))
      Next
      Return list.ToArray()
   End Function
End Module
' The example displays output similar to the following:
'       542  398  356  351  348  301  562  599  575  400  569  306
'       535  416  393  385

다음 코드 예제에서는 Find, FindLastFindAll 제네릭 메서드를 보여 줍니다. 8개의 공룡 이름을 포함하는 문자열 배열이 생성되며, 그 중 2개(위치 1과 5)는 "사우루스"로 끝납니다. 또한 코드 예제는 문자열 매개 변수를 수락하고 입력 문자열이 "saurus"로 끝나는지 여부를 나타내는 부울 값을 반환하는 검색 EndsWithSaurus조건자 메서드를 정의합니다.

제네릭 메서드는 Find 처음부터 배열을 트래버스하여 각 요소를 차례로 메서드에 EndsWithSaurus 전달합니다. 메서드가 EndsWithSaurus "Amargasaurus" 요소에 대해 반환 true 되면 검색이 중지됩니다.

참고

C#, F# 및 Visual Basic 대리자를 명시적으로 만들 Predicate<string> 필요가 없습니다(Predicate(Of String)Visual Basic). 이러한 언어는 컨텍스트에서 올바른 대리자를 유추하고 자동으로 만듭니다.

FindLast 제네릭 메서드는 끝에서 배열을 뒤로 검색하는 데 사용됩니다. 위치 5에서 요소 "딜로포사우루스"를 찾습니다. FindAll 제네릭 메서드는 "사우루스"로 끝나는 모든 요소를 포함하는 배열을 반환하는 데 사용됩니다. 요소가 표시됩니다.

또한 코드 예제에서는 제네릭 메서드와 TrueForAll 제네릭 메서드를 Exists 보여 줍니다.

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
*/
open System

// Search predicate returns true if a string ends in "saurus".
let endsWithSaurus (s: string) =
    s.Length > 5 && s.Substring(s.Length - 6).ToLower() = "saurus"

// Search predicate returns true if a string ends in "raptor".
let endsWithRaptor (s: string) =
    s.Length > 5 && s.Substring(s.Length - 6).ToLower() = "raptor"

// Search predicate returns true if a string ends in "tops".
let endsWithTops (s: string) =
    s.Length > 3 && s.Substring(s.Length - 4).ToLower() = "tops"

type DinoDiscoverySet =
    { Dinosaurs: string [] }

    member this.DiscoverAll() =
        printfn ""
        for dino in this.Dinosaurs do
            printfn $"{dino}"

    member this.DiscoverByEnding(ending: string) =
        let dinoType =
            match ending.ToLower() with
            | "raptor" -> endsWithRaptor
            | "tops" -> endsWithTops
            | "saurus" | _ -> endsWithSaurus

        Array.Exists(this.Dinosaurs, dinoType)
        |> printfn "\nArray.Exists(dinosaurs, \"%s\"): %b" ending

        Array.TrueForAll(this.Dinosaurs, dinoType)
        |> printfn "\nArray.TrueForAll(dinosaurs, \"%s\"): %b" ending

        Array.Find(this.Dinosaurs, dinoType)
        |> printfn "\nArray.Find(dinosaurs, \"%s\"): %s" ending

        Array.FindLast(this.Dinosaurs, dinoType)
        |> printfn "\nArray.FindLast(dinosaurs, \"%s\"): %s" ending

        printfn $"\nArray.FindAll(dinosaurs, \"{ending}\"):"
        for dinosaur in Array.FindAll(this.Dinosaurs, dinoType) do
            printfn $"{dinosaur}"

let dinosaurs =
    [| "Compsognathus"; "Amargasaurus"; "Oviraptor"
       "Velociraptor"; "Deinonychus"; "Dilophosaurus"
       "Gallimimus"; "Triceratops" |]

let goMesozoic = { Dinosaurs = dinosaurs }

goMesozoic.DiscoverAll()
goMesozoic.DiscoverByEnding "saurus"


// 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(Environment.NewLine + _
            "Array.Exists(dinosaurs, ""{0}""): {1}", _
            Ending, _
            Array.Exists(dinosaurs, dinoType))

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

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

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

        Console.WriteLine(Environment.NewLine + _
            "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 하는 메서드에 대한 대리자입니다. 요소는 array 개별적으로 전달 Predicate<T>되며 조건과 일치하는 요소는 반환된 배열에 저장됩니다.

이 메서드는 O(n) 연산입니다. 여기서 nLength array.

F#에서는 Array.filter 함수를 대신 사용할 수 있습니다.

적용 대상

추가 정보