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

Definicja

Określa, czy określona tablica zawiera elementy zgodne z warunkami zdefiniowanymi przez określony predykat.

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

Parametry typu

T

Typ elementów tablicy.

Parametry

array
T[]

Jednowymiarowe, zero oparte na Array wyszukiwaniu.

match
Predicate<T>

Element Predicate<T> definiujący warunki elementów do wyszukania.

Zwraca

Boolean

true jeśli array zawiera co najmniej jeden element zgodny z warunkami zdefiniowanymi przez określony predykat; w przeciwnym razie false.

Wyjątki

array to null.

-lub-

match to null.

Przykłady

Poniższy przykład określa warunki Exists dopasowania metody przy użyciu wyrażeń lambda w celu sprawdzenia, czy planeta zaczyna się od danej litery, czy też planeta znajduje się na danej tablicy.

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

W poniższym przykładzie użyto Exists metody , aby wskazać, czy nazwy w tablicy ciągów zaczynają się od określonego znaku. Przykład tworzy wystąpienie StringSearcher obiektu, przekazując ciąg w celu wyszukania jej konstruktora klasy. Metoda StringSearcher.StartsWith ma taki sam podpis jak Predicate<T> delegat. Po wywołaniu Exists metody każdy element członkowski tablicy jest przekazywany do delegata, dopóki nie zwróci true lub iteruje wszystkie elementy w tablicy.

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

Można również użyć wyrażenia lambda, a nie jawnie zdefiniować metodę, której podpis odpowiada wartości delegata. Poniższy przykład zastępuje klasę i jej StartsWith metodę StringSearcher wyrażeniem lambda.

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

Uwagi

Jest Predicate<T> delegatem do metody, która zwraca true , jeśli obiekt przekazany do niego jest zgodny z warunkami zdefiniowanymi w delegatu. Elementy elementu array są indywidualnie przekazywane do obiektu , a przetwarzanie jest zatrzymywane po znalezieniu Predicate<T>dopasowania.

Uwaga

W języku C# i Visual Basic nie jest konieczne jawne utworzenie delegataPredicate<T>. Te języki wnioskują o poprawnym delegacie z kontekstu, a następnie są tworzone automatycznie. W języku F#funkcje i wyrażenia lambda są niejawnie konwertowane.

Ta metoda jest operacją O(), gdzie n jest wartością Length array.n

Dotyczy

Zobacz też