Поделиться через


Array.IndexOf Метод

Определение

Выполняет поиск указанного объекта и возвращает индекс первого вхождения в одномерном массиве или в диапазоне элементов в массиве.

Перегрузки

Имя Описание
IndexOf(Array, Object)

Выполняет поиск указанного объекта и возвращает индекс первого вхождения в одномерном массиве.

IndexOf(Array, Object, Int32)

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения. Диапазон расширяется от указанного индекса до конца массива.

IndexOf(Array, Object, Int32, Int32)

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения ifs. Диапазон расширяется от указанного индекса для указанного количества элементов.

IndexOf<T>(T[], T, Int32)

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения. Диапазон расширяется от указанного индекса до конца массива.

IndexOf<T>(T[], T, Int32, Int32)

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения. Диапазон расширяется от указанного индекса для указанного количества элементов.

IndexOf<T>(T[], T)

Выполняет поиск указанного объекта и возвращает индекс первого вхождения в одномерном массиве.

IndexOf(Array, Object)

Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs

Выполняет поиск указанного объекта и возвращает индекс первого вхождения в одномерном массиве.

public:
 static int IndexOf(Array ^ array, System::Object ^ value);
public static int IndexOf(Array array, 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

Параметры

array
Array

Одномерный массив для поиска.

value
Object

Объект, в который нужно найти array.

Возвращаемое значение

Индекс первого вхождения value в array, если найден; в противном случае нижняя граница массива минус 1.

Исключения

array равно null.

array является многомерным.

Примеры

В примере вызывается следующие три перегрузки IndexOf метода, чтобы найти индекс строки в массиве строк:

  • IndexOf(Array, Object), чтобы определить первое вхождение строки "the" в массиве строк.

  • IndexOf(Array, Object, Int32), чтобы определить первое вхождение строки "the" в четвертом до последних элементов массива строк.

  • IndexOf(Array, Object, Int32, Int32), чтобы определить первое вхождение строки "the" в массиве строк из элемента, который следует последнему успешному совпадению к концу массива.

// 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.

Комментарии

Этот метод выполняет поиск всех элементов одномерного массива value. Чтобы определить, существует ли value в array, метод выполняет сравнение равенства с помощью сравнения EqualityComparer<T>.Defaultравенства по умолчанию.

Так как большинство массивов имеют нижнюю границу нуля, этот метод обычно возвращает -1, еслиvalue он не найден. В редких случаях нижняя граница массива равна Int32.MinValue(0x80000000) и value не найдена, этот метод возвращает Int32.MaxValue (0x7FFFFFFF).

Этот метод является операцией O(n), где n находится Length .array

См. также раздел

Применяется к

IndexOf(Array, Object, Int32)

Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения. Диапазон расширяется от указанного индекса до конца массива.

public:
 static int IndexOf(Array ^ array, System::Object ^ value, int startIndex);
public static int IndexOf(Array array, 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

Параметры

array
Array

Одномерный массив для поиска.

value
Object

Объект, в который нужно найти array.

startIndex
Int32

Начальный индекс поиска. Значение 0 (ноль) допустимо в пустом массиве.

Возвращаемое значение

Индекс первого вхождения value, если он найден, в диапазоне элементов, array которые расширяются от startIndex последнего элемента; в противном случае нижняя граница массива минус 1.

Исключения

array равно null.

startIndex находится за пределами диапазона допустимых индексов для array.

array является многомерным.

Примеры

В примере вызывается следующие три перегрузки IndexOf метода, чтобы найти индекс строки в массиве строк:

  • IndexOf(Array, Object), чтобы определить первое вхождение строки "the" в массиве строк.

  • IndexOf(Array, Object, Int32), чтобы определить первое вхождение строки "the" в четвертом до последних элементов массива строк.

  • IndexOf(Array, Object, Int32, Int32), чтобы определить первое вхождение строки "the" в массиве строк из элемента, который следует последнему успешному совпадению к концу массива.

// 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.

Комментарии

Этот метод выполняет поиск одномерного массива из элемента по индексу startIndex до последнего элемента. Чтобы определить, существует ли value в array, метод выполняет сравнение равенства с помощью сравнения EqualityComparer<T>.Defaultравенства по умолчанию.

Так как большинство массивов имеют нижнюю границу нуля, этот метод обычно возвращает -1, если value он не найден. В редких случаях нижняя граница массива равна Int32.MinValue(0x80000000) и value не найдена, этот метод возвращает Int32.MaxValue (0x7FFFFFFF).

Если startIndex равно Array.Length, метод возвращает -1. Если startIndex значение больше Array.Length, метод вызывает ArgumentOutOfRangeExceptionисключение.

Этот метод является операцией O(n), где n число элементов от startIndex конца до конца array.

См. также раздел

Применяется к

IndexOf(Array, Object, Int32, Int32)

Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения ifs. Диапазон расширяется от указанного индекса для указанного количества элементов.

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);
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

Параметры

array
Array

Одномерный массив для поиска.

value
Object

Объект, в который нужно найти array.

startIndex
Int32

Начальный индекс поиска. Значение 0 (ноль) допустимо в пустом массиве.

count
Int32

Количество элементов для поиска.

Возвращаемое значение

Индекс первого вхождения value, если он найден в индексе arraystartIndex до startIndex + count - 1; в противном случае нижняя граница массива минус 1.

Исключения

array равно null.

startIndex находится за пределами диапазона допустимых индексов для array.

–или–

count меньше нуля.

–или–

startIndex и count не указывайте допустимый раздел в array.

array является многомерным.

Примеры

В примере вызывается следующие три перегрузки IndexOf метода, чтобы найти индекс строки в массиве строк:

  • IndexOf(Array, Object), чтобы определить первое вхождение строки "the" в массиве строк.

  • IndexOf(Array, Object, Int32), чтобы определить первое вхождение строки "the" в четвертом до последних элементов массива строк.

  • IndexOf(Array, Object, Int32, Int32), чтобы определить первое вхождение строки "the" в массиве строк из элемента, который следует последнему успешному совпадению к концу массива. Чтобы определить значение аргумента count , он вычитает верхнюю границу массива из начального индекса и добавляет его.

// 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.

Комментарии

Этот метод выполняет поиск элементов одномерного массива от startIndexstartIndex плюса count минус 1, если count больше 0. Чтобы определить, существует ли value в array, метод выполняет сравнение равенства с помощью сравнения EqualityComparer<T>.Defaultравенства по умолчанию.

Так как большинство массивов имеют нижнюю границу нуля, этот метод обычно возвращает -1, когда value не найдено. В редких случаях нижняя граница массива равна Int32.MinValue (0x80000000) и value не найдена, этот метод возвращает Int32.MaxValue (0x7FFFFFFF).

Если startindex равно Array.Length, метод возвращает -1. Если startIndex значение больше Array.Length, метод вызывает ArgumentOutOfRangeExceptionисключение.

Этот метод представляет собой операцию O(n), где n находится count.

См. также раздел

Применяется к

IndexOf<T>(T[], T, Int32)

Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения. Диапазон расширяется от указанного индекса до конца массива.

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

Параметры типа

T

Тип элементов массива.

Параметры

array
T[]

Одномерный, отсчитываемый от нуля массив для поиска.

value
T

Объект, в который нужно найти array.

startIndex
Int32

Отсчитываемый от нуля начальный индекс поиска. Значение 0 (ноль) допустимо в пустом массиве.

Возвращаемое значение

Отсчитываемый от нуля индекс первого вхождения value в диапазоне элементов, array который расширяется от startIndex последнего элемента, если он найден; в противном случае — значение -1.

Исключения

array равно null.

startIndex находится за пределами диапазона допустимых индексов для array.

Примеры

В следующем примере показаны все три универсальные перегрузки IndexOf метода. Создается массив строк с одной записью, которая отображается дважды в расположении индекса 0 и расположении индекса 5. Перегрузка IndexOf<T>(T[], T) метода выполняет поиск массива с самого начала и находит первое вхождение строки. Перегрузка IndexOf<T>(T[], T, Int32) метода используется для поиска массива, начиная с расположения индекса 3 и продолжающегося до конца массива, и находит второе вхождение строки. Наконец, перегрузка IndexOf<T>(T[], T, Int32, Int32) метода используется для поиска диапазона двух записей, начиная с расположения индекса два; возвращается -1, так как в этом диапазоне нет экземпляров строки поиска.

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

Комментарии

Этот метод выполняет поиск одномерного массива из элемента в startIndex конец массива. Чтобы определить, существует ли value в array, метод выполняет сравнение равенства с помощью сравнения EqualityComparer<T>.Defaultравенства по умолчанию.

Если startIndex равно Length, метод возвращает -1. Если startIndex значение больше Array.Length, метод вызывает ArgumentOutOfRangeExceptionисключение.

Этот метод является операцией O(n), где n число элементов от startIndex конца до конца array.

См. также раздел

Применяется к

IndexOf<T>(T[], T, Int32, Int32)

Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs

Выполняет поиск указанного объекта в диапазоне элементов одномерного массива и возвращает индекс первого вхождения. Диапазон расширяется от указанного индекса для указанного количества элементов.

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

Параметры типа

T

Тип элементов массива.

Параметры

array
T[]

Одномерный, отсчитываемый от нуля массив для поиска.

value
T

Объект, в который нужно найти array.

startIndex
Int32

Отсчитываемый от нуля начальный индекс поиска. Значение 0 (ноль) допустимо в пустом массиве.

count
Int32

Количество элементов в разделе для поиска.

Возвращаемое значение

Отсчитываемый от нуля индекс первого вхождения value в диапазоне элементов, array который начинается startIndex с и содержит число элементов, указанных в count, если найдено; в противном случае — значение -1.

Исключения

array равно null.

startIndex находится за пределами диапазона допустимых индексов для array.

–или–

count меньше нуля.

–или–

startIndex и count не указывайте допустимый раздел в array.

Примеры

В следующем примере показаны все три универсальные перегрузки IndexOf метода. Создается массив строк с одной записью, которая отображается дважды в расположении индекса 0 и расположении индекса 5. Перегрузка IndexOf<T>(T[], T) метода выполняет поиск массива с самого начала и находит первое вхождение строки. Перегрузка IndexOf<T>(T[], T, Int32) метода используется для поиска массива, начиная с расположения индекса 3 и продолжающегося до конца массива, и находит второе вхождение строки. Наконец, перегрузка IndexOf<T>(T[], T, Int32, Int32) метода используется для поиска диапазона двух записей, начиная с расположения индекса два; возвращается -1, так как в этом диапазоне нет экземпляров строки поиска.

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

Комментарии

Этот метод выполняет поиск элементов одномерного массива от startIndexstartIndex плюса count минус 1, если count больше 0. Чтобы определить, существует ли value в array, метод выполняет сравнение равенства с помощью сравнения EqualityComparer<T>.Defaultравенства по умолчанию.

Если startIndex равно Array.Length, метод возвращает -1. Если startIndex значение больше Array.Length, метод вызывает ArgumentOutOfRangeExceptionисключение.

Этот метод представляет собой операцию O(n), где n находится count.

См. также раздел

Применяется к

IndexOf<T>(T[], T)

Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs
Исходный код:
Array.cs

Выполняет поиск указанного объекта и возвращает индекс первого вхождения в одномерном массиве.

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

Параметры типа

T

Тип элементов массива.

Параметры

array
T[]

Одномерный, отсчитываемый от нуля массив для поиска.

value
T

Объект, в который нужно найти array.

Возвращаемое значение

Отсчитываемый от нуля индекс первого вхождения value в целом array, если он найден; в противном случае — значение -1.

Исключения

array равно null.

Примеры

В следующем примере показаны все три универсальные перегрузки IndexOf метода. Создается массив строк с одной записью, которая отображается дважды в расположении индекса 0 и расположении индекса 5. Перегрузка IndexOf<T>(T[], T) метода выполняет поиск массива с самого начала и находит первое вхождение строки. Перегрузка IndexOf<T>(T[], T, Int32) метода используется для поиска массива, начиная с расположения индекса 3 и продолжающегося до конца массива, и находит второе вхождение строки. Наконец, перегрузка IndexOf<T>(T[], T, Int32, Int32) метода используется для поиска диапазона двух записей, начиная с расположения индекса два; возвращается -1, так как в этом диапазоне нет экземпляров строки поиска.

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

Комментарии

Этот метод выполняет поиск всех элементов одномерного массива value. Чтобы определить, существует ли value в array, метод выполняет сравнение равенства с помощью сравнения EqualityComparer<T>.Defaultравенства по умолчанию.

Этот метод является операцией O(n), где n находится Length .array

См. также раздел

Применяется к