Array.IndexOf Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Procura o objeto especificado e devolve o índice da sua primeira ocorrência num array unidimensional ou num conjunto de elementos no array.
Sobrecargas
| Name | Description |
|---|---|
| IndexOf(Array, Object) |
Procura o objeto especificado e devolve o índice da sua primeira ocorrência num array unidimensional. |
| IndexOf(Array, Object, Int32) |
Procura o objeto especificado num conjunto de elementos de um array unidimensional e retorna o índice da sua primeira ocorrência. O intervalo estende-se desde um índice especificado até ao fim do array. |
| IndexOf(Array, Object, Int32, Int32) |
Procura o objeto especificado num conjunto de elementos de um array unidimensional e devolve o índice da primeira ocorrência dos ifs. O intervalo estende-se a partir de um índice especificado para um número determinado de elementos. |
| IndexOf<T>(T[], T, Int32, Int32) |
Procura o objeto especificado num conjunto de elementos de um array unidimensional e retorna o índice da sua primeira ocorrência. O intervalo estende-se a partir de um índice especificado para um número determinado de elementos. |
| IndexOf<T>(T[], T) |
Procura o objeto especificado e devolve o índice da sua primeira ocorrência num array unidimensional. |
| IndexOf<T>(T[], T, Int32) |
Procura o objeto especificado num conjunto de elementos de um array unidimensional e devolve o índice da sua primeira ocorrência. O intervalo estende-se desde um índice especificado até ao fim do array. |
IndexOf(Array, Object)
Procura o objeto especificado e devolve o índice da sua primeira ocorrência num array unidimensional.
public:
static int IndexOf(Array ^ array, System::Object ^ value);
public static int IndexOf(Array array, object value);
static member IndexOf : Array * obj -> int
Public Shared Function IndexOf (array As Array, value As Object) As Integer
Parâmetros
- array
- Array
A matriz unidimensional para procurar.
- value
- Object
O objeto a localizar em array.
Devoluções
O índice da primeira ocorrência de value em array, se encontrado; caso contrário, o limite inferior do array menos 1.
Exceções
array é null.
array é multidimensional.
Exemplos
O exemplo chama as seguintes três sobrecargas do IndexOf método para encontrar o índice de uma cadeia num array de cadeias:
IndexOf(Array, Object), para determinar a primeira ocorrência da cadeia "the" numa matriz de cordas.
IndexOf(Array, Object, Int32), para determinar a primeira ocorrência da cadeia "the" no quarto até ao último elemento de uma matriz de cordas.
IndexOf(Array, Object, Int32, Int32), para determinar a primeira ocorrência da cadeia "the" num array de cadeias desde o elemento que segue a última correspondência bem-sucedida até ao fim do array.
// Create a string array with 3 elements having the same value.
let strings =
[| "the"; "quick"; "brown"; "fox"; "jumps"; "over"
"the"; "lazy"; "dog"; "in"; "the"; "barn" |]
// Display the elements of the array.
printfn "The array contains the following values:"
for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
printfn $" [{i,2}]: {strings[i]}"
// Search for the first occurrence of the duplicated value.
let searchString = "the"
let index = Array.IndexOf(strings, searchString)
printfn $"The first occurrence of \"{searchString}\" is at index {index}."
// Search for the first occurrence of the duplicated value in the last section of the array.
let index = Array.IndexOf(strings, searchString, 4)
printfn $"The first occurrence of \"{searchString}\" between index 4 and the end is at index {index}."
// Search for the first occurrence of the duplicated value in a section of the array.
let position = index + 1
let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1)
printfn $"The first occurrence of \"{searchString}\" between index {position} and index {strings.GetUpperBound 0} is at index {index}."
// The example displays the following output:
// The array contains the following values:
// [ 0]: the
// [ 1]: quick
// [ 2]: brown
// [ 3]: fox
// [ 4]: jumps
// [ 5]: over
// [ 6]: the
// [ 7]: lazy
// [ 8]: dog
// [ 9]: in
// [10]: the
// [11]: barn
// The first occurrence of "the" is at index 0.
// The first occurrence of "the" between index 4 and the end is at index 6.
// The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
String[] strings = { "the", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog", "in", "the",
"barn" };
// Display the elements of the array.
Console.WriteLine("The array contains the following values:");
for (int i = strings.GetLowerBound(0); i <= strings.GetUpperBound(0); i++)
Console.WriteLine(" [{0,2}]: {1}", i, strings[i]);
// Search for the first occurrence of the duplicated value.
string searchString = "the";
int index = Array.IndexOf(strings, searchString);
Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.",
searchString, index);
// Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4);
Console.WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
searchString, index);
// Search for the first occurrence of the duplicated value in a section of the array.
int position = index + 1;
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1);
Console.WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
searchString, position, strings.GetUpperBound(0), index);
// The example displays the following output:
// The array contains the following values:
// [ 0]: the
// [ 1]: quick
// [ 2]: brown
// [ 3]: fox
// [ 4]: jumps
// [ 5]: over
// [ 6]: the
// [ 7]: lazy
// [ 8]: dog
// [ 9]: in
// [10]: the
// [11]: barn
// The first occurrence of "the" is at index 0.
// The first occurrence of "the" between index 4 and the end is at index 6.
// The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example
Public Sub Main()
' Create a string array with 3 elements having the same value.
Dim strings() As String = { "the", "quick", "brown", "fox",
"jumps", "over", "the", "lazy",
"dog", "in", "the", "barn" }
' Display the values of the array.
Console.WriteLine("The array contains the following values:")
For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
Console.WriteLine(" [{0,2}]: {1}", i, strings(i))
Next
' Search for the first occurrence of the duplicated value.
Dim searchString As String = "the"
Dim index As Integer = Array.IndexOf(strings, searchString)
Console.WriteLine("The first occurrence of ""{0}"" is at index {1}.",
searchString, index)
' Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4)
Console.WriteLine("The first occurrence of ""{0}"" between index 4 and the end is at index {1}.",
searchString, index)
' Search for the first occurrence of the duplicated value in a section of the array.
Dim position As Integer = index + 1
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1)
Console.WriteLine("The first occurrence of ""{0}"" between index {1} and index {2} is at index {3}.",
searchString, position, strings.GetUpperBound(0), index)
End Sub
End Module
' The example displays the following output:
' The array contains the following values:
' [ 0]: the
' [ 1]: quick
' [ 2]: brown
' [ 3]: fox
' [ 4]: jumps
' [ 5]: over
' [ 6]: the
' [ 7]: lazy
' [ 8]: dog
' [ 9]: in
' [10]: the
' [11]: barn
' The first occurrence of "the" is at index 0.
' The first occurrence of "the" between index 4 and the end is at index 6.
' The first occurrence of "the" between index 7 and index 11 is at index 10.
Observações
Este método pesquisa todos os elementos de um array unidimensional para value. Para determinar se value existe em array, o método realiza uma comparação de igualdade usando o comparador EqualityComparer<T>.Defaultde igualdade padrão .
Como a maioria dos arrays tem um limite inferior zero, este método geralmente devolve -1 sevalue não for encontrado. No raro caso de o limite inferior do array ser igual a Int32.MinValue(0x80000000) e value não ser encontrado, este método devolve Int32.MaxValue (0x7FFFFFFF).
Este método é uma operação O(n), onde n é o Length de array.
Ver também
Aplica-se a
IndexOf(Array, Object, Int32)
Procura o objeto especificado num conjunto de elementos de um array unidimensional e retorna o índice da sua primeira ocorrência. O intervalo estende-se desde um índice especificado até ao fim do array.
public:
static int IndexOf(Array ^ array, System::Object ^ value, int startIndex);
public static int IndexOf(Array array, object value, int startIndex);
static member IndexOf : Array * obj * int -> int
Public Shared Function IndexOf (array As Array, value As Object, startIndex As Integer) As Integer
Parâmetros
- array
- Array
A matriz unidimensional para procurar.
- value
- Object
O objeto a localizar em array.
- startIndex
- Int32
O índice inicial da pesquisa. 0 (zero) é válido num array vazio.
Devoluções
O índice da primeira ocorrência de value, se for encontrado, dentro do intervalo de elementos em array que se estende de startIndex até ao último elemento; caso contrário, o limite inferior do array menos 1.
Exceções
array é null.
startIndex está fora do intervalo de índices válidos para array.
array é multidimensional.
Exemplos
O exemplo chama as seguintes três sobrecargas do IndexOf método para encontrar o índice de uma cadeia num array de cadeias:
IndexOf(Array, Object), para determinar a primeira ocorrência da cadeia "the" numa matriz de cordas.
IndexOf(Array, Object, Int32), para determinar a primeira ocorrência da cadeia "the" no quarto até ao último elemento de uma matriz de cordas.
IndexOf(Array, Object, Int32, Int32), para determinar a primeira ocorrência da cadeia "the" num array de cadeias desde o elemento que segue a última correspondência bem-sucedida até ao fim do array.
// Create a string array with 3 elements having the same value.
let strings =
[| "the"; "quick"; "brown"; "fox"; "jumps"; "over"
"the"; "lazy"; "dog"; "in"; "the"; "barn" |]
// Display the elements of the array.
printfn "The array contains the following values:"
for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
printfn $" [{i,2}]: {strings[i]}"
// Search for the first occurrence of the duplicated value.
let searchString = "the"
let index = Array.IndexOf(strings, searchString)
printfn $"The first occurrence of \"{searchString}\" is at index {index}."
// Search for the first occurrence of the duplicated value in the last section of the array.
let index = Array.IndexOf(strings, searchString, 4)
printfn $"The first occurrence of \"{searchString}\" between index 4 and the end is at index {index}."
// Search for the first occurrence of the duplicated value in a section of the array.
let position = index + 1
let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1)
printfn $"The first occurrence of \"{searchString}\" between index {position} and index {strings.GetUpperBound 0} is at index {index}."
// The example displays the following output:
// The array contains the following values:
// [ 0]: the
// [ 1]: quick
// [ 2]: brown
// [ 3]: fox
// [ 4]: jumps
// [ 5]: over
// [ 6]: the
// [ 7]: lazy
// [ 8]: dog
// [ 9]: in
// [10]: the
// [11]: barn
// The first occurrence of "the" is at index 0.
// The first occurrence of "the" between index 4 and the end is at index 6.
// The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
String[] strings = { "the", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog", "in", "the",
"barn" };
// Display the elements of the array.
Console.WriteLine("The array contains the following values:");
for (int i = strings.GetLowerBound(0); i <= strings.GetUpperBound(0); i++)
Console.WriteLine(" [{0,2}]: {1}", i, strings[i]);
// Search for the first occurrence of the duplicated value.
string searchString = "the";
int index = Array.IndexOf(strings, searchString);
Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.",
searchString, index);
// Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4);
Console.WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
searchString, index);
// Search for the first occurrence of the duplicated value in a section of the array.
int position = index + 1;
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1);
Console.WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
searchString, position, strings.GetUpperBound(0), index);
// The example displays the following output:
// The array contains the following values:
// [ 0]: the
// [ 1]: quick
// [ 2]: brown
// [ 3]: fox
// [ 4]: jumps
// [ 5]: over
// [ 6]: the
// [ 7]: lazy
// [ 8]: dog
// [ 9]: in
// [10]: the
// [11]: barn
// The first occurrence of "the" is at index 0.
// The first occurrence of "the" between index 4 and the end is at index 6.
// The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example
Public Sub Main()
' Create a string array with 3 elements having the same value.
Dim strings() As String = { "the", "quick", "brown", "fox",
"jumps", "over", "the", "lazy",
"dog", "in", "the", "barn" }
' Display the values of the array.
Console.WriteLine("The array contains the following values:")
For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
Console.WriteLine(" [{0,2}]: {1}", i, strings(i))
Next
' Search for the first occurrence of the duplicated value.
Dim searchString As String = "the"
Dim index As Integer = Array.IndexOf(strings, searchString)
Console.WriteLine("The first occurrence of ""{0}"" is at index {1}.",
searchString, index)
' Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4)
Console.WriteLine("The first occurrence of ""{0}"" between index 4 and the end is at index {1}.",
searchString, index)
' Search for the first occurrence of the duplicated value in a section of the array.
Dim position As Integer = index + 1
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1)
Console.WriteLine("The first occurrence of ""{0}"" between index {1} and index {2} is at index {3}.",
searchString, position, strings.GetUpperBound(0), index)
End Sub
End Module
' The example displays the following output:
' The array contains the following values:
' [ 0]: the
' [ 1]: quick
' [ 2]: brown
' [ 3]: fox
' [ 4]: jumps
' [ 5]: over
' [ 6]: the
' [ 7]: lazy
' [ 8]: dog
' [ 9]: in
' [10]: the
' [11]: barn
' The first occurrence of "the" is at index 0.
' The first occurrence of "the" between index 4 and the end is at index 6.
' The first occurrence of "the" between index 7 and index 11 is at index 10.
Observações
Este método pesquisa um array unidimensional desde o elemento no índice startIndex até ao último elemento. Para determinar se value existe em array, o método realiza uma comparação de igualdade usando o comparador EqualityComparer<T>.Defaultde igualdade padrão .
Como a maioria dos arrays tem um limite inferior zero, este método geralmente devolve -1 se value não for encontrado. No raro caso de o limite inferior do array ser igual a Int32.MinValue(0x80000000) e value não ser encontrado, este método devolve Int32.MaxValue (0x7FFFFFFF).
Se startIndex for Array.Lengthigual a , o método retorna -1. Se startIndex for maior que Array.Length, o método lança um ArgumentOutOfRangeException.
Este método é uma operação O(n), onde n é o número de elementos de startIndex até ao fim de array.
Ver também
Aplica-se a
IndexOf(Array, Object, Int32, Int32)
Procura o objeto especificado num conjunto de elementos de um array unidimensional e devolve o índice da primeira ocorrência dos ifs. O intervalo estende-se a partir de um índice especificado para um número determinado de elementos.
public:
static int IndexOf(Array ^ array, System::Object ^ value, int startIndex, int count);
public static int IndexOf(Array array, object value, int startIndex, int count);
static member IndexOf : Array * obj * int * int -> int
Public Shared Function IndexOf (array As Array, value As Object, startIndex As Integer, count As Integer) As Integer
Parâmetros
- array
- Array
A matriz unidimensional para procurar.
- value
- Object
O objeto a localizar em array.
- startIndex
- Int32
O índice inicial da pesquisa. 0 (zero) é válido num array vazio.
- count
- Int32
O número de elementos a pesquisar.
Devoluções
O índice da primeira ocorrência de value, se for encontrado em do array índice startIndex de - startIndex + count 1; caso contrário, o limite inferior do array menos 1.
Exceções
array é null.
startIndex está fora do intervalo de índices válidos para array.
-ou-
count é inferior a zero.
-ou-
startIndex e count não especificam uma secção válida em array.
array é multidimensional.
Exemplos
O exemplo chama as seguintes três sobrecargas do IndexOf método para encontrar o índice de uma cadeia num array de cadeias:
IndexOf(Array, Object), para determinar a primeira ocorrência da cadeia "the" numa matriz de cordas.
IndexOf(Array, Object, Int32), para determinar a primeira ocorrência da cadeia "the" no quarto até ao último elemento de uma matriz de cordas.
IndexOf(Array, Object, Int32, Int32), para determinar a primeira ocorrência da cadeia "the" num array de cadeias desde o elemento que segue a última correspondência bem-sucedida até ao fim do array. Para determinar o valor do
countargumento, subtrai o limite superior do array do índice inicial e soma um.
// Create a string array with 3 elements having the same value.
let strings =
[| "the"; "quick"; "brown"; "fox"; "jumps"; "over"
"the"; "lazy"; "dog"; "in"; "the"; "barn" |]
// Display the elements of the array.
printfn "The array contains the following values:"
for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
printfn $" [{i,2}]: {strings[i]}"
// Search for the first occurrence of the duplicated value.
let searchString = "the"
let index = Array.IndexOf(strings, searchString)
printfn $"The first occurrence of \"{searchString}\" is at index {index}."
// Search for the first occurrence of the duplicated value in the last section of the array.
let index = Array.IndexOf(strings, searchString, 4)
printfn $"The first occurrence of \"{searchString}\" between index 4 and the end is at index {index}."
// Search for the first occurrence of the duplicated value in a section of the array.
let position = index + 1
let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1)
printfn $"The first occurrence of \"{searchString}\" between index {position} and index {strings.GetUpperBound 0} is at index {index}."
// The example displays the following output:
// The array contains the following values:
// [ 0]: the
// [ 1]: quick
// [ 2]: brown
// [ 3]: fox
// [ 4]: jumps
// [ 5]: over
// [ 6]: the
// [ 7]: lazy
// [ 8]: dog
// [ 9]: in
// [10]: the
// [11]: barn
// The first occurrence of "the" is at index 0.
// The first occurrence of "the" between index 4 and the end is at index 6.
// The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
String[] strings = { "the", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog", "in", "the",
"barn" };
// Display the elements of the array.
Console.WriteLine("The array contains the following values:");
for (int i = strings.GetLowerBound(0); i <= strings.GetUpperBound(0); i++)
Console.WriteLine(" [{0,2}]: {1}", i, strings[i]);
// Search for the first occurrence of the duplicated value.
string searchString = "the";
int index = Array.IndexOf(strings, searchString);
Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.",
searchString, index);
// Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4);
Console.WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
searchString, index);
// Search for the first occurrence of the duplicated value in a section of the array.
int position = index + 1;
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1);
Console.WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
searchString, position, strings.GetUpperBound(0), index);
// The example displays the following output:
// The array contains the following values:
// [ 0]: the
// [ 1]: quick
// [ 2]: brown
// [ 3]: fox
// [ 4]: jumps
// [ 5]: over
// [ 6]: the
// [ 7]: lazy
// [ 8]: dog
// [ 9]: in
// [10]: the
// [11]: barn
// The first occurrence of "the" is at index 0.
// The first occurrence of "the" between index 4 and the end is at index 6.
// The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example
Public Sub Main()
' Create a string array with 3 elements having the same value.
Dim strings() As String = { "the", "quick", "brown", "fox",
"jumps", "over", "the", "lazy",
"dog", "in", "the", "barn" }
' Display the values of the array.
Console.WriteLine("The array contains the following values:")
For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
Console.WriteLine(" [{0,2}]: {1}", i, strings(i))
Next
' Search for the first occurrence of the duplicated value.
Dim searchString As String = "the"
Dim index As Integer = Array.IndexOf(strings, searchString)
Console.WriteLine("The first occurrence of ""{0}"" is at index {1}.",
searchString, index)
' Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4)
Console.WriteLine("The first occurrence of ""{0}"" between index 4 and the end is at index {1}.",
searchString, index)
' Search for the first occurrence of the duplicated value in a section of the array.
Dim position As Integer = index + 1
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1)
Console.WriteLine("The first occurrence of ""{0}"" between index {1} and index {2} is at index {3}.",
searchString, position, strings.GetUpperBound(0), index)
End Sub
End Module
' The example displays the following output:
' The array contains the following values:
' [ 0]: the
' [ 1]: quick
' [ 2]: brown
' [ 3]: fox
' [ 4]: jumps
' [ 5]: over
' [ 6]: the
' [ 7]: lazy
' [ 8]: dog
' [ 9]: in
' [10]: the
' [11]: barn
' The first occurrence of "the" is at index 0.
' The first occurrence of "the" between index 4 and the end is at index 6.
' The first occurrence of "the" between index 7 and index 11 is at index 10.
Observações
Este método procura os elementos de um array unidimensional de startIndex até startIndex mais count menos 1, se count for maior que 0. Para determinar se value existe em array, o método realiza uma comparação de igualdade usando o comparador EqualityComparer<T>.Defaultde igualdade padrão .
Como a maioria dos arrays tem um limite inferior zero, este método geralmente devolve -1 quando value não é encontrado. No raro caso de o limite inferior do array ser igual a Int32.MinValue (0x80000000) e value não ser encontrado, este método retorna Int32.MaxValue (0x7FFFFFFF).
Se startindex for Array.Lengthigual a , o método devolve -1. Se startIndex for maior que Array.Length, o método lança um ArgumentOutOfRangeException.
Este método é uma operação O(n), onde n é count.
Ver também
Aplica-se a
IndexOf<T>(T[], T, Int32, Int32)
Procura o objeto especificado num conjunto de elementos de um array unidimensional e retorna o índice da sua primeira ocorrência. O intervalo estende-se a partir de um índice especificado para um número determinado de elementos.
public:
generic <typename T>
static int IndexOf(cli::array <T> ^ array, T value, int startIndex, int count);
public static int IndexOf<T>(T[] array, T value, int startIndex, int count);
static member IndexOf : 'T[] * 'T * int * int -> int
Public Shared Function IndexOf(Of T) (array As T(), value As T, startIndex As Integer, count As Integer) As Integer
Parâmetros de Tipo Genérico
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O array unidimensional, baseado em zero, para pesquisar.
- value
- T
O objeto a localizar em array.
- startIndex
- Int32
O índice inicial baseado em zero da pesquisa. 0 (zero) é válido num array vazio.
- count
- Int32
O número de elementos na secção a pesquisar.
Devoluções
O índice baseado em zero da primeira ocorrência de value dentro do intervalo de elementos em array que começa em startIndex e contém o número de elementos especificados em count, se encontrados; caso contrário, -1.
Exceções
array é null.
startIndex está fora do intervalo de índices válidos para array.
-ou-
count é inferior a zero.
-ou-
startIndex e count não especificam uma secção válida em array.
Exemplos
O exemplo seguinte demonstra as três sobrecargas genéricas do IndexOf método. É criada uma matriz de cadeias, com uma entrada que aparece duas vezes, na localização do índice 0 e na localização do índice 5. A IndexOf<T>(T[], T) sobrecarga do método pesquisa o array desde o início e encontra a primeira ocorrência da cadeia. A IndexOf<T>(T[], T, Int32) sobrecarga do método é usada para procurar o array começando com a localização do índice 3 e continuando até ao fim do array, encontrando a segunda ocorrência da cadeia. Finalmente, a IndexOf<T>(T[], T, Int32, Int32) sobrecarga de métodos é usada para pesquisar um intervalo de duas entradas, começando na localização de índice dois; devolve -1 porque não existem instâncias da cadeia de pesquisa nesse intervalo.
string[] dinosaurs = { "Tyrannosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Brachiosaurus",
"Deinonychus",
"Tyrannosaurus",
"Compsognathus" };
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus"));
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3));
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));
/* This code example produces the following output:
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus
Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
*/
open System
let dinosaurs =
[| "Tyrannosaurus"
"Amargasaurus"
"Mamenchisaurus"
"Brachiosaurus"
"Deinonychus"
"Tyrannosaurus"
"Compsognathus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
Array.IndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): %i"
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): %i"
// This code example produces the following output:
//
// Tyrannosaurus
// Amargasaurus
// Mamenchisaurus
// Brachiosaurus
// Deinonychus
// Tyrannosaurus
// Compsognathus
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { "Tyrannosaurus", _
"Amargasaurus", _
"Mamenchisaurus", _
"Brachiosaurus", _
"Deinonychus", _
"Tyrannosaurus", _
"Compsognathus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus"))
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3))
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 2, 2): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2))
End Sub
End Class
' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Observações
Este método procura os elementos de um array unidimensional de startIndex até startIndex mais count menos 1, se count for maior que 0. Para determinar se value existe em array, o método realiza uma comparação de igualdade usando o comparador EqualityComparer<T>.Defaultde igualdade padrão .
Se startIndex for Array.Lengthigual a , o método devolve -1. Se startIndex for maior que Array.Length, o método lança um ArgumentOutOfRangeException.
Este método é uma operação O(n), onde n é count.
Ver também
Aplica-se a
IndexOf<T>(T[], T)
Procura o objeto especificado e devolve o índice da sua primeira ocorrência num array unidimensional.
public:
generic <typename T>
static int IndexOf(cli::array <T> ^ array, T value);
public static int IndexOf<T>(T[] array, T value);
static member IndexOf : 'T[] * 'T -> int
Public Shared Function IndexOf(Of T) (array As T(), value As T) As Integer
Parâmetros de Tipo Genérico
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O array unidimensional, baseado em zero, para pesquisar.
- value
- T
O objeto a localizar em array.
Devoluções
O índice baseado em zero da primeira ocorrência de value em todo arrayo , se encontrado; caso contrário, -1.
Exceções
array é null.
Exemplos
O exemplo seguinte demonstra as três sobrecargas genéricas do IndexOf método. É criada uma matriz de cadeias, com uma entrada que aparece duas vezes, na localização do índice 0 e na localização do índice 5. A IndexOf<T>(T[], T) sobrecarga do método pesquisa o array desde o início e encontra a primeira ocorrência da cadeia. A IndexOf<T>(T[], T, Int32) sobrecarga do método é usada para procurar o array começando com a localização do índice 3 e continuando até ao fim do array, encontrando a segunda ocorrência da cadeia. Finalmente, a IndexOf<T>(T[], T, Int32, Int32) sobrecarga de métodos é usada para pesquisar um intervalo de duas entradas, começando na localização de índice dois; devolve -1 porque não existem instâncias da cadeia de pesquisa nesse intervalo.
string[] dinosaurs = { "Tyrannosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Brachiosaurus",
"Deinonychus",
"Tyrannosaurus",
"Compsognathus" };
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus"));
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3));
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));
/* This code example produces the following output:
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus
Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
*/
open System
let dinosaurs =
[| "Tyrannosaurus"
"Amargasaurus"
"Mamenchisaurus"
"Brachiosaurus"
"Deinonychus"
"Tyrannosaurus"
"Compsognathus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
Array.IndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): %i"
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): %i"
// This code example produces the following output:
//
// Tyrannosaurus
// Amargasaurus
// Mamenchisaurus
// Brachiosaurus
// Deinonychus
// Tyrannosaurus
// Compsognathus
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { "Tyrannosaurus", _
"Amargasaurus", _
"Mamenchisaurus", _
"Brachiosaurus", _
"Deinonychus", _
"Tyrannosaurus", _
"Compsognathus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus"))
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3))
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 2, 2): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2))
End Sub
End Class
' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Observações
Este método pesquisa todos os elementos de um array unidimensional para value. Para determinar se value existe em array, o método realiza uma comparação de igualdade usando o comparador EqualityComparer<T>.Defaultde igualdade padrão .
Este método é uma operação O(n), onde n é o Length de array.
Ver também
Aplica-se a
IndexOf<T>(T[], T, Int32)
Procura o objeto especificado num conjunto de elementos de um array unidimensional e devolve o índice da sua primeira ocorrência. O intervalo estende-se desde um índice especificado até ao fim do array.
public:
generic <typename T>
static int IndexOf(cli::array <T> ^ array, T value, int startIndex);
public static int IndexOf<T>(T[] array, T value, int startIndex);
static member IndexOf : 'T[] * 'T * int -> int
Public Shared Function IndexOf(Of T) (array As T(), value As T, startIndex As Integer) As Integer
Parâmetros de Tipo Genérico
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O array unidimensional, baseado em zero, para pesquisar.
- value
- T
O objeto a localizar em array.
- startIndex
- Int32
O índice inicial baseado em zero da pesquisa. 0 (zero) é válido num array vazio.
Devoluções
O índice baseado em zero da primeira ocorrência de value dentro do intervalo de elementos em array que se estende de startIndex até ao último elemento, se encontrado; caso contrário, -1.
Exceções
array é null.
startIndex está fora do intervalo de índices válidos para array.
Exemplos
O exemplo seguinte demonstra as três sobrecargas genéricas do IndexOf método. É criada uma matriz de cadeias, com uma entrada que aparece duas vezes, na localização do índice 0 e na localização do índice 5. A IndexOf<T>(T[], T) sobrecarga do método pesquisa o array desde o início e encontra a primeira ocorrência da cadeia. A IndexOf<T>(T[], T, Int32) sobrecarga do método é usada para procurar o array começando com a localização do índice 3 e continuando até ao fim do array, encontrando a segunda ocorrência da cadeia. Finalmente, a IndexOf<T>(T[], T, Int32, Int32) sobrecarga de métodos é usada para pesquisar um intervalo de duas entradas, começando na localização de índice dois; devolve -1 porque não existem instâncias da cadeia de pesquisa nesse intervalo.
string[] dinosaurs = { "Tyrannosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Brachiosaurus",
"Deinonychus",
"Tyrannosaurus",
"Compsognathus" };
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus"));
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3));
Console.WriteLine(
"\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}",
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));
/* This code example produces the following output:
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus
Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
*/
open System
let dinosaurs =
[| "Tyrannosaurus"
"Amargasaurus"
"Mamenchisaurus"
"Brachiosaurus"
"Deinonychus"
"Tyrannosaurus"
"Compsognathus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
Array.IndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): %i"
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): %i"
// This code example produces the following output:
//
// Tyrannosaurus
// Amargasaurus
// Mamenchisaurus
// Brachiosaurus
// Deinonychus
// Tyrannosaurus
// Compsognathus
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
//
// Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { "Tyrannosaurus", _
"Amargasaurus", _
"Mamenchisaurus", _
"Brachiosaurus", _
"Deinonychus", _
"Tyrannosaurus", _
"Compsognathus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus"))
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus", 3))
Console.WriteLine(vbLf & _
"Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 2, 2): {0}", _
Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2))
End Sub
End Class
' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Observações
Este método pesquisa um array unidimensional desde o elemento em startIndex até ao final do array. Para determinar se value existe em array, o método realiza uma comparação de igualdade usando o comparador EqualityComparer<T>.Defaultde igualdade padrão .
Se startIndex for Lengthigual a , o método retorna -1. Se startIndex for maior que Array.Length, o método lança um ArgumentOutOfRangeException.
Este método é uma operação O(n), onde n é o número de elementos de startIndex até ao fim de array.