Array.Exists<T>(T[], Predicate<T>) 方法

定義

判斷指定的陣列是否包含符合指定之述詞 (Predicate) 所定義的條件之項目。

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[]

要搜尋的一維且以零為起始的 Array

match
Predicate<T>

定義搜尋項目之條件的 Predicate<T>

傳回

Boolean

如果 array 包含的一或多個項目符合指定述詞所定義的條件,則為 true,否則為 false

例外狀況

arraynull

-或-

matchnull

範例

下列範例會使用 Lambda 運算式指定 方法的比對條件 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

您也可以使用 Lambda 運算式,而不是明確定義簽章對應至委派的方法。 下列範例會 StringSearcher 以 Lambda 運算式取代 類別及其 StartsWith 方法。

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# 中,函式和 Lambda 運算式會隱含地轉換。

這個方法是 O (n) 作業,其中 nLengtharray

適用於

另請參閱