Array.LastIndexOf Метод

Определение

Возвращает индекс последнего вхождения значения в одномерном Array или в части Arrayзначения.

Перегрузки

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

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

LastIndexOf(Array, Object, Int32)

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

LastIndexOf(Array, Object, Int32, Int32)

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

LastIndexOf<T>(T[], T)

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

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

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

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

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

LastIndexOf(Array, Object)

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

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

public:
 static int LastIndexOf(Array ^ array, System::Object ^ value);
public static int LastIndexOf(Array array, object value);
public static int LastIndexOf(Array array, object? value);
static member LastIndexOf : Array * obj -> int
Public Shared Function LastIndexOf (array As Array, value As Object) As Integer

Параметры

array
Array

Одномерный Array поиск.

value
Object

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

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

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

Исключения

array равно null.

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

Примеры

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

let printIndexAndValues (arr: 'a []) =
   for i = arr.GetLowerBound 0 to arr.GetUpperBound 0 do
      printfn $"\t[{i}]:\t{arr[i]}"

// Creates and initializes a new Array with three elements of the same value.
let myArray = 
   [| "the"; "quick"; "brown"; "fox"
      "jumps"; "over"; "the"; "lazy"
      "dog"; "in"; "the"; "barn" |]

// Displays the values of the Array.
printfn "The Array contains the following values:"
printIndexAndValues myArray

// Searches for the last occurrence of the duplicated value.
let myString = "the"
let myIndex = Array.LastIndexOf(myArray, myString)
printfn $"The last occurrence of \"{myString}\" is at index {myIndex}."

// Searches for the last occurrence of the duplicated value in the first section of the Array.
let myIndex = Array.LastIndexOf(myArray, myString, 8)
printfn $"The last occurrence of \"{myString}\" between the start and index 8 is at index {myIndex}."

// Searches for the last occurrence of the duplicated value in a section of the Array.
// Note that the start index is greater than the end index because the search is done backward.
let myIndex = Array.LastIndexOf( myArray, myString, 10, 6 )
printfn $"The last occurrence of \"{myString}\" between index 5 and index 10 is at index {myIndex}."


//      This code produces 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 last occurrence of "the" is at index 10.
//      The last occurrence of "the" between the start and index 8 is at index 6.
//      The last occurrence of "the" between index 5 and index 10 is at index 10.
// Creates and initializes a new Array with three elements of the same value.
Array myArray=Array.CreateInstance( typeof(string), 12 );
myArray.SetValue( "the", 0 );
myArray.SetValue( "quick", 1 );
myArray.SetValue( "brown", 2 );
myArray.SetValue( "fox", 3 );
myArray.SetValue( "jumps", 4 );
myArray.SetValue( "over", 5 );
myArray.SetValue( "the", 6 );
myArray.SetValue( "lazy", 7 );
myArray.SetValue( "dog", 8 );
myArray.SetValue( "in", 9 );
myArray.SetValue( "the", 10 );
myArray.SetValue( "barn", 11 );

// Displays the values of the Array.
Console.WriteLine( "The Array contains the following values:" );
PrintIndexAndValues( myArray );

// Searches for the last occurrence of the duplicated value.
string myString = "the";
int myIndex = Array.LastIndexOf( myArray, myString );
Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );

// Searches for the last occurrence of the duplicated value in the first section of the Array.
myIndex = Array.LastIndexOf( myArray, myString, 8 );
Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex );

// Searches for the last occurrence of the duplicated value in a section of the Array.
// Note that the start index is greater than the end index because the search is done backward.
myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
Console.WriteLine( "The last occurrence of \"{0}\" between index 5 and index 10 is at index {1}.", myString, myIndex );

void PrintIndexAndValues( Array anArray )  {
   for ( int i = anArray.GetLowerBound(0); i <= anArray.GetUpperBound(0); i++ )
      Console.WriteLine( "\t[{0}]:\t{1}", i, anArray.GetValue( i ) );
}

/*
This code produces 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 last occurrence of "the" is at index 10.
The last occurrence of "the" between the start and index 8 is at index 6.
The last occurrence of "the" between index 5 and index 10 is at index 10.
*/
Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Array with three elements of
        ' the same value.
        Dim myArray As Array = Array.CreateInstance(GetType(String), 12)
        myArray.SetValue("the", 0)
        myArray.SetValue("quick", 1)
        myArray.SetValue("brown", 2)
        myArray.SetValue("fox", 3)
        myArray.SetValue("jumps", 4)
        myArray.SetValue("over", 5)
        myArray.SetValue("the", 6)
        myArray.SetValue("lazy", 7)
        myArray.SetValue("dog", 8)
        myArray.SetValue("in", 9)
        myArray.SetValue("the", 10)
        myArray.SetValue("barn", 11)
        
        ' Displays the values of the Array.
        Console.WriteLine("The Array contains the following values:")
        PrintIndexAndValues(myArray)
        
        ' Searches for the last occurrence of the duplicated value.
        Dim myString As String = "the"
        Dim myIndex As Integer = Array.LastIndexOf(myArray, myString)
        Console.WriteLine("The last occurrence of ""{0}"" is at index {1}.", _
           myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in the first
        ' section of the Array.
        myIndex = Array.LastIndexOf(myArray, myString, 8)
        Console.WriteLine("The last occurrence of ""{0}"" between the start " _
           + "and index 8 is at index {1}.", myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in a section
        ' of the Array.  Note that the start index is greater than the end
        ' index because the search is done backward.
        myIndex = Array.LastIndexOf(myArray, myString, 10, 6)
        Console.WriteLine("The last occurrence of ""{0}"" between index 5 " _
           + "and index 10 is at index {1}.", myString, myIndex)
    End Sub
    
    
    Public Shared Sub PrintIndexAndValues(myArray As Array)
        Dim i As Integer
        For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
            Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab _
               + "{1}", i, myArray.GetValue(i))
        Next i
    End Sub
End Class

' This code produces 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 last occurrence of "the" is at index 10.
' The last occurrence of "the" between the start and index 8 is at index 6.
' The last occurrence of "the" between index 5 and index 10 is at index 10.

Комментарии

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

Элементы сравниваются с указанным значением с помощью Object.Equals метода. Если тип элемента является неинтринсичным (определяемым пользователем), Equals используется реализация этого типа.

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

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

Этот метод использует Equals методы и CompareTo методы Array , чтобы определить, существует ли Object указанный value параметром.

CompareTo item методы параметра для объектов в коллекции.

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

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

LastIndexOf(Array, Object, Int32)

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

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

public:
 static int LastIndexOf(Array ^ array, System::Object ^ value, int startIndex);
public static int LastIndexOf(Array array, object value, int startIndex);
public static int LastIndexOf(Array array, object? value, int startIndex);
static member LastIndexOf : Array * obj * int -> int
Public Shared Function LastIndexOf (array As Array, value As Object, startIndex As Integer) As Integer

Параметры

array
Array

Одномерный Array поиск.

value
Object

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

startIndex
Int32

Начальный индекс обратного поиска.

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

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

Исключения

array равно null.

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

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

Примеры

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

let printIndexAndValues (arr: 'a []) =
   for i = arr.GetLowerBound 0 to arr.GetUpperBound 0 do
      printfn $"\t[{i}]:\t{arr[i]}"

// Creates and initializes a new Array with three elements of the same value.
let myArray = 
   [| "the"; "quick"; "brown"; "fox"
      "jumps"; "over"; "the"; "lazy"
      "dog"; "in"; "the"; "barn" |]

// Displays the values of the Array.
printfn "The Array contains the following values:"
printIndexAndValues myArray

// Searches for the last occurrence of the duplicated value.
let myString = "the"
let myIndex = Array.LastIndexOf(myArray, myString)
printfn $"The last occurrence of \"{myString}\" is at index {myIndex}."

// Searches for the last occurrence of the duplicated value in the first section of the Array.
let myIndex = Array.LastIndexOf(myArray, myString, 8)
printfn $"The last occurrence of \"{myString}\" between the start and index 8 is at index {myIndex}."

// Searches for the last occurrence of the duplicated value in a section of the Array.
// Note that the start index is greater than the end index because the search is done backward.
let myIndex = Array.LastIndexOf( myArray, myString, 10, 6 )
printfn $"The last occurrence of \"{myString}\" between index 5 and index 10 is at index {myIndex}."


//      This code produces 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 last occurrence of "the" is at index 10.
//      The last occurrence of "the" between the start and index 8 is at index 6.
//      The last occurrence of "the" between index 5 and index 10 is at index 10.
// Creates and initializes a new Array with three elements of the same value.
Array myArray=Array.CreateInstance( typeof(string), 12 );
myArray.SetValue( "the", 0 );
myArray.SetValue( "quick", 1 );
myArray.SetValue( "brown", 2 );
myArray.SetValue( "fox", 3 );
myArray.SetValue( "jumps", 4 );
myArray.SetValue( "over", 5 );
myArray.SetValue( "the", 6 );
myArray.SetValue( "lazy", 7 );
myArray.SetValue( "dog", 8 );
myArray.SetValue( "in", 9 );
myArray.SetValue( "the", 10 );
myArray.SetValue( "barn", 11 );

// Displays the values of the Array.
Console.WriteLine( "The Array contains the following values:" );
PrintIndexAndValues( myArray );

// Searches for the last occurrence of the duplicated value.
string myString = "the";
int myIndex = Array.LastIndexOf( myArray, myString );
Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );

// Searches for the last occurrence of the duplicated value in the first section of the Array.
myIndex = Array.LastIndexOf( myArray, myString, 8 );
Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex );

// Searches for the last occurrence of the duplicated value in a section of the Array.
// Note that the start index is greater than the end index because the search is done backward.
myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
Console.WriteLine( "The last occurrence of \"{0}\" between index 5 and index 10 is at index {1}.", myString, myIndex );

void PrintIndexAndValues( Array anArray )  {
   for ( int i = anArray.GetLowerBound(0); i <= anArray.GetUpperBound(0); i++ )
      Console.WriteLine( "\t[{0}]:\t{1}", i, anArray.GetValue( i ) );
}

/*
This code produces 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 last occurrence of "the" is at index 10.
The last occurrence of "the" between the start and index 8 is at index 6.
The last occurrence of "the" between index 5 and index 10 is at index 10.
*/
Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Array with three elements of
        ' the same value.
        Dim myArray As Array = Array.CreateInstance(GetType(String), 12)
        myArray.SetValue("the", 0)
        myArray.SetValue("quick", 1)
        myArray.SetValue("brown", 2)
        myArray.SetValue("fox", 3)
        myArray.SetValue("jumps", 4)
        myArray.SetValue("over", 5)
        myArray.SetValue("the", 6)
        myArray.SetValue("lazy", 7)
        myArray.SetValue("dog", 8)
        myArray.SetValue("in", 9)
        myArray.SetValue("the", 10)
        myArray.SetValue("barn", 11)
        
        ' Displays the values of the Array.
        Console.WriteLine("The Array contains the following values:")
        PrintIndexAndValues(myArray)
        
        ' Searches for the last occurrence of the duplicated value.
        Dim myString As String = "the"
        Dim myIndex As Integer = Array.LastIndexOf(myArray, myString)
        Console.WriteLine("The last occurrence of ""{0}"" is at index {1}.", _
           myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in the first
        ' section of the Array.
        myIndex = Array.LastIndexOf(myArray, myString, 8)
        Console.WriteLine("The last occurrence of ""{0}"" between the start " _
           + "and index 8 is at index {1}.", myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in a section
        ' of the Array.  Note that the start index is greater than the end
        ' index because the search is done backward.
        myIndex = Array.LastIndexOf(myArray, myString, 10, 6)
        Console.WriteLine("The last occurrence of ""{0}"" between index 5 " _
           + "and index 10 is at index {1}.", myString, myIndex)
    End Sub
    
    
    Public Shared Sub PrintIndexAndValues(myArray As Array)
        Dim i As Integer
        For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
            Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab _
               + "{1}", i, myArray.GetValue(i))
        Next i
    End Sub
End Class

' This code produces 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 last occurrence of "the" is at index 10.
' The last occurrence of "the" between the start and index 8 is at index 6.
' The last occurrence of "the" between index 5 and index 10 is at index 10.

Комментарии

Одномерный Array поиск выполняется в обратном направлении, начиная startIndex с первого элемента.

Элементы сравниваются с указанным значением с помощью Object.Equals метода. Если тип элемента является неинтринсичным (определяемым пользователем), Equals используется реализация этого типа.

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

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

Этот метод использует Equals методы и CompareTo методы Array , чтобы определить, существует ли Object указанный value параметром.

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

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

LastIndexOf(Array, Object, Int32, Int32)

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

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

public:
 static int LastIndexOf(Array ^ array, System::Object ^ value, int startIndex, int count);
public static int LastIndexOf(Array array, object value, int startIndex, int count);
public static int LastIndexOf(Array array, object? value, int startIndex, int count);
static member LastIndexOf : Array * obj * int * int -> int
Public Shared Function LastIndexOf (array As Array, value As Object, startIndex As Integer, count As Integer) As Integer

Параметры

array
Array

Одномерный Array поиск.

value
Object

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

startIndex
Int32

Начальный индекс обратного поиска.

count
Int32

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

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

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

Исключения

array равно null.

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

-или-

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

-или-

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

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

Примеры

В следующем примере кода показано, как определить индекс последнего вхождения указанного элемента в массиве. Обратите внимание, что LastIndexOf метод является обратным поиском, count поэтому должен быть меньше или равен (startIndex минус нижняя граница массива плюс 1).

let printIndexAndValues (arr: 'a []) =
   for i = arr.GetLowerBound 0 to arr.GetUpperBound 0 do
      printfn $"\t[{i}]:\t{arr[i]}"

// Creates and initializes a new Array with three elements of the same value.
let myArray = 
   [| "the"; "quick"; "brown"; "fox"
      "jumps"; "over"; "the"; "lazy"
      "dog"; "in"; "the"; "barn" |]

// Displays the values of the Array.
printfn "The Array contains the following values:"
printIndexAndValues myArray

// Searches for the last occurrence of the duplicated value.
let myString = "the"
let myIndex = Array.LastIndexOf(myArray, myString)
printfn $"The last occurrence of \"{myString}\" is at index {myIndex}."

// Searches for the last occurrence of the duplicated value in the first section of the Array.
let myIndex = Array.LastIndexOf(myArray, myString, 8)
printfn $"The last occurrence of \"{myString}\" between the start and index 8 is at index {myIndex}."

// Searches for the last occurrence of the duplicated value in a section of the Array.
// Note that the start index is greater than the end index because the search is done backward.
let myIndex = Array.LastIndexOf( myArray, myString, 10, 6 )
printfn $"The last occurrence of \"{myString}\" between index 5 and index 10 is at index {myIndex}."


//      This code produces 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 last occurrence of "the" is at index 10.
//      The last occurrence of "the" between the start and index 8 is at index 6.
//      The last occurrence of "the" between index 5 and index 10 is at index 10.
// Creates and initializes a new Array with three elements of the same value.
Array myArray=Array.CreateInstance( typeof(string), 12 );
myArray.SetValue( "the", 0 );
myArray.SetValue( "quick", 1 );
myArray.SetValue( "brown", 2 );
myArray.SetValue( "fox", 3 );
myArray.SetValue( "jumps", 4 );
myArray.SetValue( "over", 5 );
myArray.SetValue( "the", 6 );
myArray.SetValue( "lazy", 7 );
myArray.SetValue( "dog", 8 );
myArray.SetValue( "in", 9 );
myArray.SetValue( "the", 10 );
myArray.SetValue( "barn", 11 );

// Displays the values of the Array.
Console.WriteLine( "The Array contains the following values:" );
PrintIndexAndValues( myArray );

// Searches for the last occurrence of the duplicated value.
string myString = "the";
int myIndex = Array.LastIndexOf( myArray, myString );
Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );

// Searches for the last occurrence of the duplicated value in the first section of the Array.
myIndex = Array.LastIndexOf( myArray, myString, 8 );
Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex );

// Searches for the last occurrence of the duplicated value in a section of the Array.
// Note that the start index is greater than the end index because the search is done backward.
myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
Console.WriteLine( "The last occurrence of \"{0}\" between index 5 and index 10 is at index {1}.", myString, myIndex );

void PrintIndexAndValues( Array anArray )  {
   for ( int i = anArray.GetLowerBound(0); i <= anArray.GetUpperBound(0); i++ )
      Console.WriteLine( "\t[{0}]:\t{1}", i, anArray.GetValue( i ) );
}

/*
This code produces 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 last occurrence of "the" is at index 10.
The last occurrence of "the" between the start and index 8 is at index 6.
The last occurrence of "the" between index 5 and index 10 is at index 10.
*/
Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Array with three elements of
        ' the same value.
        Dim myArray As Array = Array.CreateInstance(GetType(String), 12)
        myArray.SetValue("the", 0)
        myArray.SetValue("quick", 1)
        myArray.SetValue("brown", 2)
        myArray.SetValue("fox", 3)
        myArray.SetValue("jumps", 4)
        myArray.SetValue("over", 5)
        myArray.SetValue("the", 6)
        myArray.SetValue("lazy", 7)
        myArray.SetValue("dog", 8)
        myArray.SetValue("in", 9)
        myArray.SetValue("the", 10)
        myArray.SetValue("barn", 11)
        
        ' Displays the values of the Array.
        Console.WriteLine("The Array contains the following values:")
        PrintIndexAndValues(myArray)
        
        ' Searches for the last occurrence of the duplicated value.
        Dim myString As String = "the"
        Dim myIndex As Integer = Array.LastIndexOf(myArray, myString)
        Console.WriteLine("The last occurrence of ""{0}"" is at index {1}.", _
           myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in the first
        ' section of the Array.
        myIndex = Array.LastIndexOf(myArray, myString, 8)
        Console.WriteLine("The last occurrence of ""{0}"" between the start " _
           + "and index 8 is at index {1}.", myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in a section
        ' of the Array.  Note that the start index is greater than the end
        ' index because the search is done backward.
        myIndex = Array.LastIndexOf(myArray, myString, 10, 6)
        Console.WriteLine("The last occurrence of ""{0}"" between index 5 " _
           + "and index 10 is at index {1}.", myString, myIndex)
    End Sub
    
    
    Public Shared Sub PrintIndexAndValues(myArray As Array)
        Dim i As Integer
        For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
            Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab _
               + "{1}", i, myArray.GetValue(i))
        Next i
    End Sub
End Class

' This code produces 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 last occurrence of "the" is at index 10.
' The last occurrence of "the" between the start and index 8 is at index 6.
' The last occurrence of "the" between index 5 and index 10 is at index 10.

Комментарии

Одномерный Array поиск выполняется в обратном направлении начиная startIndex с startIndex минуса count плюс 1, если count больше 0.

Элементы сравниваются с указанным значением с помощью Object.Equals метода. Если тип элемента является неинтринсичным (определяемым пользователем),Equals используется реализация этого типа.

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

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

Этот метод использует Equals методы и CompareTo методы Array , чтобы определить, существует ли Object указанный value параметром.

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

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

LastIndexOf<T>(T[], T)

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

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

public:
generic <typename T>
 static int LastIndexOf(cli::array <T> ^ array, T value);
public static int LastIndexOf<T>(T[] array, T value);
static member LastIndexOf : 'T[] * 'T -> int
Public Shared Function LastIndexOf(Of T) (array As T(), value As T) As Integer

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

T

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

Параметры

array
T[]

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

value
T

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

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

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

Исключения

array равно null.

Примеры

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

string[] dinosaurs = { "Tyrannosaurus",
    "Amargasaurus",
    "Mamenchisaurus",
    "Brachiosaurus",
    "Deinonychus",
    "Tyrannosaurus",
    "Compsognathus" };

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus"));

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3));

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 4, 4): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4));

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -1
*/
open System

let dinosaurs = 
    [| "Tyrannosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Brachiosaurus"
       "Deinonychus"
       "Tyrannosaurus"
       "Compsognathus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): %i"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4)
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 4, 4): %i"

// This code example produces the following output:
//    
//    Tyrannosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Brachiosaurus
//    Deinonychus
//    Tyrannosaurus
//    Compsognathus
//    
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5
//
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0
//
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"))

        Console.WriteLine(vbLf & _
            "Array.LastIndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3))

        Console.WriteLine(vbLf & _
            "Array.LastIndexOf(dinosaurs, ""Tyrannosaurus"", 4, 4): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4))

    End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -1

Комментарии

Выполняется Array поиск назад, начиная с последнего элемента и заканчивающийся первым элементом.

Элементы сравниваются с указанным значением с помощью Object.Equals метода. Если тип элемента является неинтринсичным (определяемым пользователем), Equals используется реализация этого типа.

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

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

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

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

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

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

public:
generic <typename T>
 static int LastIndexOf(cli::array <T> ^ array, T value, int startIndex);
public static int LastIndexOf<T>(T[] array, T value, int startIndex);
static member LastIndexOf : 'T[] * 'T * int -> int
Public Shared Function LastIndexOf(Of T) (array As T(), value As T, startIndex As Integer) As Integer

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

T

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

Параметры

array
T[]

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

value
T

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

startIndex
Int32

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

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

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

Исключения

array равно null.

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

Примеры

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

string[] dinosaurs = { "Tyrannosaurus",
    "Amargasaurus",
    "Mamenchisaurus",
    "Brachiosaurus",
    "Deinonychus",
    "Tyrannosaurus",
    "Compsognathus" };

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus"));

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3));

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 4, 4): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4));

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -1
*/
open System

let dinosaurs = 
    [| "Tyrannosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Brachiosaurus"
       "Deinonychus"
       "Tyrannosaurus"
       "Compsognathus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): %i"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4)
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 4, 4): %i"

// This code example produces the following output:
//    
//    Tyrannosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Brachiosaurus
//    Deinonychus
//    Tyrannosaurus
//    Compsognathus
//    
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5
//
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0
//
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"))

        Console.WriteLine(vbLf & _
            "Array.LastIndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3))

        Console.WriteLine(vbLf & _
            "Array.LastIndexOf(dinosaurs, ""Tyrannosaurus"", 4, 4): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4))

    End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -1

Комментарии

Выполняется Array поиск назад, начиная startIndex с первого элемента и заканчивающийся.

Элементы сравниваются с указанным значением с помощью Object.Equals метода. Если тип элемента является неинтринсичным (определяемым пользователем), Equals используется реализация этого типа.

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

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

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

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

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

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

public:
generic <typename T>
 static int LastIndexOf(cli::array <T> ^ array, T value, int startIndex, int count);
public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count);
static member LastIndexOf : 'T[] * 'T * int * int -> int
Public Shared Function LastIndexOf(Of T) (array As T(), value As T, startIndex As Integer, count As Integer) As Integer

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

T

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

Параметры

array
T[]

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

value
T

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

startIndex
Int32

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

count
Int32

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

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

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

Исключения

array равно null.

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

-или-

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

-или-

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

Примеры

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

string[] dinosaurs = { "Tyrannosaurus",
    "Amargasaurus",
    "Mamenchisaurus",
    "Brachiosaurus",
    "Deinonychus",
    "Tyrannosaurus",
    "Compsognathus" };

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus"));

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3));

Console.WriteLine(
    "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 4, 4): {0}",
    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4));

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -1
*/
open System

let dinosaurs = 
    [| "Tyrannosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Brachiosaurus"
       "Deinonychus"
       "Tyrannosaurus"
       "Compsognathus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): %i"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4)
|> printfn "\nArray.LastIndexOf(dinosaurs, \"Tyrannosaurus\", 4, 4): %i"

// This code example produces the following output:
//    
//    Tyrannosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Brachiosaurus
//    Deinonychus
//    Tyrannosaurus
//    Compsognathus
//    
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5
//
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0
//
//    Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"))

        Console.WriteLine(vbLf & _
            "Array.LastIndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3))

        Console.WriteLine(vbLf & _
            "Array.LastIndexOf(dinosaurs, ""Tyrannosaurus"", 4, 4): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4))

    End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0
'
'Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -1

Комментарии

Выполняется Array поиск назад, начиная startIndex с startIndex минус count плюс 1, если count больше 0.

Элементы сравниваются с указанным значением с помощью Object.Equals метода. Если тип элемента является неинтринсичным (определяемым пользователем), Equals используется реализация этого типа.

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

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

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