Array.FindAll<T>(T[], Predicate<T>) Metodo
Definizione
Recupera tutti gli elementi che soddisfano le condizioni definite nel predicato specificato.Retrieves all the elements that match the conditions defined by the specified predicate.
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()
Parametri di tipo
- T
Tipo degli elementi della matrice.The type of the elements of the array.
Parametri
- array
- T[]
Oggetto Array unidimensionale in base zero in cui eseguire la ricerca.The one-dimensional, zero-based Array to search.
- match
- Predicate<T>
Oggetto Predicate<T> che definisce le condizioni degli elementi da cercare.The Predicate<T> that defines the conditions of the elements to search for.
Restituisce
- T[]
Oggetto Array contenente tutti gli elementi che corrispondono alle condizioni definite dal predicato specificato, se presente; in caso contrario, un oggetto Array vuoto.An Array containing all the elements that match the conditions defined by the specified predicate, if found; otherwise, an empty Array.
Eccezioni
Esempio
Nell'esempio seguente viene creata una matrice di 50 numeri casuali con valori che possono variare da 0 a 1.000.The following example creates an array of 50 random numbers with values that can range from 0 to 1,000. Chiama quindi il FindAll metodo con un'espressione lambda che restituisce i valori compresi tra 300 e 600.It then calls the FindAll method with a lambda expression that returns the values that range from 300 to 600. Si noti che all'espressione lambda viene passato un parametro denominato x
; rappresenta il singolo membro della matrice che viene passato a Predicate<T> .Note that the lambda expression is passed a parameter named x
; this represents the individual array member that is passed to the Predicate<T>. Si noti inoltre che le lBound
variabili locali e uBound
sono accessibili all'interno dell'espressione lambda.Also note that the local lBound
and uBound
variables are accessible within the lambda expression.
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
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
Nell'esempio di codice riportato di seguito vengono illustrati i Find FindLast FindAll metodi generici, e.The following code example demonstrates the Find, FindLast, and FindAll generic methods. Viene creata una matrice di stringhe che contiene 8 nomi di dinosauri, due dei quali (nelle posizioni 1 e 5) terminano con "saurus".An array of strings is created, containing 8 dinosaur names, two of which (at positions 1 and 5) end with "saurus". Nell'esempio di codice viene inoltre definito un metodo del predicato di ricerca denominato EndsWithSaurus
, che accetta un parametro di stringa e restituisce un valore booleano che indica se la stringa di input termina in "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".
Il Find metodo generico attraversa la matrice dall'inizio, passando ogni elemento a sua volta al EndsWithSaurus
metodo.The Find generic method traverses the array from the beginning, passing each element in turn to the EndsWithSaurus
method. La ricerca si interrompe quando il EndsWithSaurus
metodo restituisce true
per l'elemento "Amargasaurus".The search stops when the EndsWithSaurus
method returns true
for the element "Amargasaurus".
Nota
In C# e Visual Basic non è necessario creare in Predicate<string>
Predicate(Of String)
modo esplicito il delegato (in Visual Basic).In C# and Visual Basic, it is not necessary to create the Predicate<string>
delegate (Predicate(Of String)
in Visual Basic) explicitly. Questi linguaggi deducono il delegato corretto dal contesto e lo creano automaticamente.These languages infer the correct delegate from context and create it automatically.
Il FindLast metodo generico viene usato per cercare la matrice all'indietro rispetto alla fine.The FindLast generic method is used to search the array backward from the end. Trova l'elemento "Dilophosaurus" nella posizione 5.It finds the element "Dilophosaurus" at position 5. Il FindAll metodo generico viene usato per restituire una matrice contenente tutti gli elementi che terminano con "saurus".The FindAll generic method is used to return an array containing all the elements that end in "saurus". Gli elementi vengono visualizzati.The elements are displayed.
Nell'esempio di codice vengono inoltre illustrati i Exists TrueForAll metodi generici e.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(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
Commenti
Predicate<T>È un delegato di un metodo che restituisce true
se l'oggetto passato a esso corrisponde alle condizioni definite nel delegato.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. Gli elementi di array
vengono passati singolarmente a Predicate<T> e gli elementi che soddisfano le condizioni vengono salvati nella matrice restituita.The elements of array
are individually passed to the Predicate<T>, and the elements that match the conditions are saved in the returned array.
Questo metodo è un'operazione O ( n
), dove n
è l'oggetto Length di array
.This method is an O(n
) operation, where n
is the Length of array
.