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

정의

지정한 배열에 지정한 조건자에 정의된 조건과 일치하는 요소가 포함되어 있는지를 확인합니다.

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

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

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

match
Predicate<T>

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

반환

Boolean

array에 지정한 조건자에 정의된 조건과 일치하는 하나 이상의 요소가 포함되어 있으면 true이고, 그렇지 않으면 false입니다.

예외

array이(가) null인 경우

또는

match이(가) null인 경우

예제

다음 예제에서는 람다 식을 사용하여 행성이 지정된 문자로 시작하는지 또는 지정된 배열에서 행성이 있는지 여부를 확인하는 메서드의 일치 조건을 Exists 지정합니다.

using System;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] planets = { "Mercury", "Venus",
                "Earth", "Mars", "Jupiter",
                "Saturn", "Uranus", "Neptune" };

            Console.WriteLine("One or more planets begin with 'M': {0}",
                Array.Exists(planets, element => element.StartsWith("M")));

            Console.WriteLine("One or more planets begin with 'T': {0}",
                Array.Exists(planets, element => element.StartsWith("T")));

            Console.WriteLine("Is Pluto one of the planets? {0}",
                Array.Exists(planets, element => element == "Pluto"));
        }
    }
}
// The example displays the following output:
//       One or more planets begin with 'M': True
//       One or more planets begin with 'T': False
//       Is Pluto one of the planets? False
open System

let  planets = 
    [| "Mercury"; "Venus"
       "Earth"; "Mars"; "Jupiter"
       "Saturn"; "Uranus"; "Neptune" |]

Array.Exists(planets, fun element -> element.StartsWith "M")
|> printfn "One or more planets begin with 'M': %O"

Array.Exists(planets, fun element -> element.StartsWith "T")
|> printfn "One or more planets begin with 'T': %O"

Array.Exists(planets, fun element -> element = "Pluto")
|> printfn "Is Pluto one of the planets? %O"

// The example displays the following output:
//       One or more planets begin with 'M': True
//       One or more planets begin with 'T': False
//       Is Pluto one of the planets? False
Module Example
    Public Sub Main()
        Dim planets() As String = {"Mercury", "Venus",
                                    "Earth", "Mars", "Jupiter",
                                    "Saturn", "Uranus", "Neptune"}

        Console.WriteLine("One or more planets begin with 'M': {0}",
            Array.Exists(planets, Function(element)
                                      Return element.StartsWith("M")
                                  End Function))

        Console.WriteLine("One or more planets begin with 'T': {0}",
            Array.Exists(planets, Function(element)
                                      Return element.StartsWith("T")
                                  End Function))

        Console.WriteLine("Is Pluto one of the planets? {0}",
            Array.Exists(planets, Function(element)
                                      Return element.Equals("Pluto")
                                  End Function))

    End Sub
End Module
' The example displays the following output:
'       One or more planets begin with 'M': True
'       One or more planets begin with 'T': False
'       Is Pluto one of the planets? False

다음 예제에서는 메서드를 Exists 사용하여 문자열 배열의 이름이 지정된 문자로 시작하는지 여부를 나타냅니다. 이 예제에서는 검색할 문자열을 StringSearcher 해당 클래스 생성자에 전달하여 개체를 인스턴스화합니다. 메서드는 StringSearcher.StartsWith 대리자 서명과 Predicate<T> 동일합니다. 메서드가 Exists 호출되면 배열의 모든 요소를 반환 true 하거나 반복할 때까지 배열의 각 멤버가 대리자에 전달됩니다.

using System;

public class Example
{
   public static void Main()
   {
      String[] names = { "Adam", "Adel", "Bridgette", "Carla",
                         "Charles", "Daniel", "Elaine", "Frances",
                         "George", "Gillian", "Henry", "Irving",
                         "James", "Janae", "Lawrence", "Miguel",
                         "Nicole", "Oliver", "Paula", "Robert",
                         "Stephen", "Thomas", "Vanessa",
                         "Veronica", "Wilberforce" };
      Char[] charsToFind = { 'A', 'K', 'W', 'Z' };

      foreach (var charToFind in charsToFind)
         Console.WriteLine("One or more names begin with '{0}': {1}",
                           charToFind,
                           Array.Exists(names, (new StringSearcher(charToFind)).StartsWith));
   }
}

public class StringSearcher
{
   char firstChar;

   public StringSearcher(char firstChar)
   {
      this.firstChar = char.ToUpper(firstChar);
   }

   public bool StartsWith(string s)
   {
      if (string.IsNullOrEmpty(s)) return false;

      if(s.Substring(0, 1).ToUpper() == firstChar.ToString())
         return true;
      else
         return false;
   }
}
// The example displays the following output:
//       One or more names begin with 'A': True
//       One or more names begin with 'K': False
//       One or more names begin with 'W': True
//       One or more names begin with 'Z': False
open System

type StringSearcher(firstChar) =
    member _.StartsWith(s) =
        if String.IsNullOrEmpty s then 
            false 
        else
            s.Substring(0, 1).ToUpper() = string firstChar

let names = 
    [| "Adam"; "Adel"; "Bridgette"; "Carla";
       "Charles"; "Daniel"; "Elaine"; "Frances"
       "George"; "Gillian"; "Henry"; "Irving"
       "James"; "Janae"; "Lawrence"; "Miguel"
       "Nicole"; "Oliver"; "Paula"; "Robert"
       "Stephen"; "Thomas"; "Vanessa"
       "Veronica"; "Wilberforce" |]

let charsToFind = [ 'A'; 'K'; 'W'; 'Z' ]

for char in charsToFind do 
    let exists = Array.Exists(names, fun x -> StringSearcher(char).StartsWith x)
    // let exists = Array.exists (StringSearcher(char).StartsWith) names
    printfn $"One or more names begin with '{char}': {exists}"

// The example displays the following output:
//       One or more names begin with 'A': True
//       One or more names begin with 'K': False
//       One or more names begin with 'W': True
//       One or more names begin with 'Z': False
Module Example
   Public Sub Main()
      Dim names() As String = { "Adam", "Adel", "Bridgette", "Carla",
                                "Charles", "Daniel", "Elaine", "Frances",
                                "George", "Gillian", "Henry", "Irving",
                                "James", "Janae", "Lawrence", "Miguel",
                                "Nicole", "Oliver", "Paula", "Robert",
                                "Stephen", "Thomas", "Vanessa",
                                "Veronica", "Wilberforce" }
      Dim charsToFind() As Char = { "A"c, "K"c, "W"c, "Z"c }
      
      For Each charToFind In charsToFind
         Console.WriteLine("One or more names begin with '{0}': {1}",
                           charToFind,
                           Array.Exists(names, AddressOf (New StringSearcher(charToFind)).StartsWith))
      Next
   End Sub
   
End Module

Public Class StringSearcher
   Dim firstChar As Char
   
   Public Sub New(firstChar As Char)
      Me.firstChar = Char.ToUpper(firstChar)
   End Sub
   
   Public Function StartsWith(s As String) As Boolean
      If String.IsNullOrEmpty(s) Then Return False
      
      If s.Substring(0, 1).ToUpper = firstChar Then
         Return True
      Else
         Return False
      End If
   End Function
End Class
' The example displays the following output:
'       One or more names begin with 'A': True
'       One or more names begin with 'K': False
'       One or more names begin with 'W': True
'       One or more names begin with 'Z': False

시그니처가 대리자의 서명에 해당하는 메서드를 명시적으로 정의하는 대신 람다 식을 사용할 수도 있습니다. 다음 예제에서는 클래스와 해당 StartsWith 메서드를 StringSearcher 람다 식으로 바꿉니다.

using System;

public class Example
{
   public static void Main()
   {
      String[] names = { "Adam", "Adel", "Bridgette", "Carla",
                         "Charles", "Daniel", "Elaine", "Frances",
                         "George", "Gillian", "Henry", "Irving",
                         "James", "Janae", "Lawrence", "Miguel",
                         "Nicole", "Oliver", "Paula", "Robert",
                         "Stephen", "Thomas", "Vanessa",
                         "Veronica", "Wilberforce" };
      Char[] charsToFind = { 'A', 'K', 'W', 'Z' };

      foreach (var charToFind in charsToFind)
         Console.WriteLine("One or more names begin with '{0}': {1}",
                           charToFind,
                           Array.Exists(names,
                                        s => { if (string.IsNullOrEmpty(s))
                                                  return false;

                                               if (s.Substring(0, 1).ToUpper() == charToFind.ToString())
                                                  return true;
                                               else
                                                  return false;
                                             } ));
   }
}
// The example displays the following output:
//       One or more names begin with 'A': True
//       One or more names begin with 'K': False
//       One or more names begin with 'W': True
//       One or more names begin with 'Z': False
open System

let names = 
    [| "Adam"; "Adel"; "Bridgette"; "Carla";
       "Charles"; "Daniel"; "Elaine"; "Frances"
       "George"; "Gillian"; "Henry"; "Irving"
       "James"; "Janae"; "Lawrence"; "Miguel"
       "Nicole"; "Oliver"; "Paula"; "Robert"
       "Stephen"; "Thomas"; "Vanessa"
       "Veronica"; "Wilberforce" |]

let charsToFind = [ 'A'; 'K'; 'W'; 'Z' ]

for char in charsToFind do
    let exists = 
        Array.Exists(names, fun s -> 
            if String.IsNullOrEmpty s then false 
            else s.Substring(0, 1).ToUpper() = string char)

    printfn $"One or more names begin with '{char}': {exists}"
                    
// The example displays the following output:
//       One or more names begin with 'A': True
//       One or more names begin with 'K': False
//       One or more names begin with 'W': True
//       One or more names begin with 'Z': False
Module Example
   Public Sub Main()
      Dim names() As String = { "Adam", "Adel", "Bridgette", "Carla",
                                "Charles", "Daniel", "Elaine", "Frances",
                                "George", "Gillian", "Henry", "Irving",
                                "James", "Janae", "Lawrence", "Miguel",
                                "Nicole", "Oliver", "Paula", "Robert",
                                "Stephen", "Thomas", "Vanessa",
                                "Veronica", "Wilberforce" }
      Dim charsToFind() As Char = { "A"c, "K"c, "W"c, "Z"c }

      For Each charToFind In charsToFind
         Console.WriteLine("One or more names begin with '{0}': {1}",
                           charToFind,
                           Array.Exists(names, Function(s)
                                                  If String.IsNullOrEmpty(s) Then Return False

                                                  If s.Substring(0, 1).ToUpper = charToFind Then
                                                     Return True
                                                  Else
                                                     Return False
                                                  End If
                                               End Function ))
      Next
   End Sub
End Module
' The example displays the following output:
'       One or more names begin with 'A': True
'       One or more names begin with 'K': False
'       One or more names begin with 'W': True
'       One or more names begin with 'Z': False

설명

전달 Predicate<T> 된 개체가 대리자에서 정의된 조건과 일치하는지 반환 true 하는 메서드에 대한 대리자입니다. 요소는 array 개별적으로 전달되며 Predicate<T>일치 항목이 발견되면 처리가 중지됩니다.

참고

C# 및 Visual Basic 대리자를 명시적으로 만들 Predicate<T> 필요는 없습니다. 이러한 언어는 컨텍스트에서 올바른 대리자를 유추하고 자동으로 만듭니다. F#에서 함수 및 람다 식은 암시적으로 변환됩니다.

이 메서드는 O(n) 연산이며 여기서 n 는 .의 arrayLength 연산입니다.

적용 대상

추가 정보