Collection<T>.IndexOf(T) Collection<T>.IndexOf(T) Collection<T>.IndexOf(T) Collection<T>.IndexOf(T) Method

정의

지정된 개체를 검색하고, 전체 Collection<T>에서 처음으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다.Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>.

public:
 virtual int IndexOf(T item);
public int IndexOf (T item);
abstract member IndexOf : 'T -> int
override this.IndexOf : 'T -> int
Public Function IndexOf (item As T) As Integer

매개 변수

item
T T T T

List<T>에서 찾을 개체입니다.The object to locate in the List<T>. 참조 형식에 대해 값은 null이 될 수 있습니다.The value can be null for reference types.

반환

item가 있으면 전체 Collection<T>에서 맨 처음 발견되는 값의 0부터 시작하는 인덱스이고, 그렇지 않으면 -1입니다.The zero-based index of the first occurrence of item within the entire Collection<T>, if found; otherwise, -1.

구현

예제

다음 코드 예제 대부분의 속성 및 메서드의 Collection<T>합니다.The following code example demonstrates many of the properties and methods of Collection<T>. 코드 예제에서는 문자열을 사용 하 여 컬렉션을 만듭니다는 Add 여러 문자열을 추가 하는 메서드 표시는 Count는 문자열을 나열 합니다.The code example creates a collection of strings, uses the Add method to add several strings, displays the Count, and lists the strings. 이 예제에서는 사용 합니다 IndexOf 메서드는 문자열의 인덱스를 및 Contains 문자열 컬렉션에 있는지 확인 하는 방법입니다.The example uses the IndexOf method to find the index of a string and the Contains method to determine whether a string is in the collection. 사용 하 여 문자열을 삽입 하는 예제는 Insert 기본값을 사용 하는 메서드 및 검색 설정 문자열 Item[Int32] 속성 (C# 인덱서).The example inserts a string using the Insert method and retrieves and sets strings using the default Item[Int32] property (the indexer in C#). 예제에서는 문자열 identity를 사용 하 여 문자열을 제거 합니다 Remove 메서드 및 인덱스를 사용 하 여는 RemoveAt 메서드.The example removes strings by string identity using the Remove method and by index using the RemoveAt method. 마지막으로 Clear 메서드는 컬렉션에서 모든 문자열을 지우는 데 사용 됩니다.Finally, the Clear method is used to clear all strings from the collection.

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

public ref class Demo
{
public:
    static void Main()
    {
        Collection<String^>^ dinosaurs = gcnew Collection<String^>();

        dinosaurs->Add("Psitticosaurus");
        dinosaurs->Add("Caudipteryx");
        dinosaurs->Add("Compsognathus");
        dinosaurs->Add("Muttaburrasaurus");

        Console::WriteLine("{0} dinosaurs:", dinosaurs->Count);
        Display(dinosaurs);

        Console::WriteLine("\nIndexOf(\"Muttaburrasaurus\"): {0}",
            dinosaurs->IndexOf("Muttaburrasaurus"));

        Console::WriteLine("\nContains(\"Caudipteryx\"): {0}",
            dinosaurs->Contains("Caudipteryx"));

        Console::WriteLine("\nInsert(2, \"Nanotyrannus\")");
        dinosaurs->Insert(2, "Nanotyrannus");
        Display(dinosaurs);

        Console::WriteLine("\ndinosaurs[2]: {0}", dinosaurs[2]);

        Console::WriteLine("\ndinosaurs[2] = \"Microraptor\"");
        dinosaurs[2] = "Microraptor";
        Display(dinosaurs);

        Console::WriteLine("\nRemove(\"Microraptor\")");
        dinosaurs->Remove("Microraptor");
        Display(dinosaurs);

        Console::WriteLine("\nRemoveAt(0)");
        dinosaurs->RemoveAt(0);
        Display(dinosaurs);

        Console::WriteLine("\ndinosaurs.Clear()");
        dinosaurs->Clear();
        Console::WriteLine("Count: {0}", dinosaurs->Count);
    }

private:
    static void Display(Collection<String^>^ cs)
    {
        Console::WriteLine();
        for each( String^ item in cs )
        {
            Console::WriteLine(item);
        }
    }
};

int main()
{
    Demo::Main();
}

/* This code example produces the following output:

4 dinosaurs:

Psitticosaurus
Caudipteryx
Compsognathus
Muttaburrasaurus

IndexOf("Muttaburrasaurus"): 3

Contains("Caudipteryx"): True

Insert(2, "Nanotyrannus")

Psitticosaurus
Caudipteryx
Nanotyrannus
Compsognathus
Muttaburrasaurus

dinosaurs[2]: Nanotyrannus

dinosaurs[2] = "Microraptor"

Psitticosaurus
Caudipteryx
Microraptor
Compsognathus
Muttaburrasaurus

Remove("Microraptor")

Psitticosaurus
Caudipteryx
Compsognathus
Muttaburrasaurus

RemoveAt(0)

Caudipteryx
Compsognathus
Muttaburrasaurus

dinosaurs.Clear()
Count: 0
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> dinosaurs = new Collection<string>();

        dinosaurs.Add("Psitticosaurus");
        dinosaurs.Add("Caudipteryx");
        dinosaurs.Add("Compsognathus");
        dinosaurs.Add("Muttaburrasaurus");

        Console.WriteLine("{0} dinosaurs:", dinosaurs.Count);
        Display(dinosaurs);
    
        Console.WriteLine("\nIndexOf(\"Muttaburrasaurus\"): {0}", 
            dinosaurs.IndexOf("Muttaburrasaurus"));

        Console.WriteLine("\nContains(\"Caudipteryx\"): {0}", 
            dinosaurs.Contains("Caudipteryx"));

        Console.WriteLine("\nInsert(2, \"Nanotyrannus\")");
        dinosaurs.Insert(2, "Nanotyrannus");
        Display(dinosaurs);

        Console.WriteLine("\ndinosaurs[2]: {0}", dinosaurs[2]);

        Console.WriteLine("\ndinosaurs[2] = \"Microraptor\"");
        dinosaurs[2] = "Microraptor";
        Display(dinosaurs);

        Console.WriteLine("\nRemove(\"Microraptor\")");
        dinosaurs.Remove("Microraptor");
        Display(dinosaurs);

        Console.WriteLine("\nRemoveAt(0)");
        dinosaurs.RemoveAt(0);
        Display(dinosaurs);

        Console.WriteLine("\ndinosaurs.Clear()");
        dinosaurs.Clear();
        Console.WriteLine("Count: {0}", dinosaurs.Count);
    }
    
    private static void Display(Collection<string> cs)
    {
        Console.WriteLine();
        foreach( string item in cs )
        {
            Console.WriteLine(item);
        }
    }
}

/* This code example produces the following output:

4 dinosaurs:

Psitticosaurus
Caudipteryx
Compsognathus
Muttaburrasaurus

IndexOf("Muttaburrasaurus"): 3

Contains("Caudipteryx"): True

Insert(2, "Nanotyrannus")

Psitticosaurus
Caudipteryx
Nanotyrannus
Compsognathus
Muttaburrasaurus

dinosaurs[2]: Nanotyrannus

dinosaurs[2] = "Microraptor"

Psitticosaurus
Caudipteryx
Microraptor
Compsognathus
Muttaburrasaurus

Remove("Microraptor")

Psitticosaurus
Caudipteryx
Compsognathus
Muttaburrasaurus

RemoveAt(0)

Caudipteryx
Compsognathus
Muttaburrasaurus

dinosaurs.Clear()
Count: 0
 */
Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Public Class Demo
    
    Public Shared Sub Main() 

        Dim dinosaurs As New Collection(Of String)

        dinosaurs.Add("Psitticosaurus")
        dinosaurs.Add("Caudipteryx")
        dinosaurs.Add("Compsognathus")
        dinosaurs.Add("Muttaburrasaurus")

        Console.WriteLine("{0} dinosaurs:", dinosaurs.Count)
        Display(dinosaurs)
    
        Console.WriteLine(vbLf & "IndexOf(""Muttaburrasaurus""): {0}", _
            dinosaurs.IndexOf("Muttaburrasaurus"))

        Console.WriteLine(vbLf & "Contains(""Caudipteryx""): {0}", _
            dinosaurs.Contains("Caudipteryx"))

        Console.WriteLine(vbLf & "Insert(2, ""Nanotyrannus"")")
        dinosaurs.Insert(2, "Nanotyrannus")
        Display(dinosaurs)

        Console.WriteLine(vbLf & "dinosaurs(2): {0}", dinosaurs(2))

        Console.WriteLine(vbLf & "dinosaurs(2) = ""Microraptor""")
        dinosaurs(2) = "Microraptor"
        Display(dinosaurs)

        Console.WriteLine(vbLf & "Remove(""Microraptor"")")
        dinosaurs.Remove("Microraptor")
        Display(dinosaurs)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        dinosaurs.RemoveAt(0)
        Display(dinosaurs)
 
        Console.WriteLine(vbLf & "dinosaurs.Clear()")
        dinosaurs.Clear()
        Console.WriteLine("Count: {0}", dinosaurs.Count)

    End Sub
    
    Private Shared Sub Display(ByVal cs As Collection(Of String)) 
        Console.WriteLine()
        For Each item As String In cs
            Console.WriteLine(item)
        Next item
    End Sub
End Class

' This code example produces the following output:
'
'4 dinosaurs:
'
'Psitticosaurus
'Caudipteryx
'Compsognathus
'Muttaburrasaurus
'
'IndexOf("Muttaburrasaurus"): 3
'
'Contains("Caudipteryx"): True
'
'Insert(2, "Nanotyrannus")
'
'Psitticosaurus
'Caudipteryx
'Nanotyrannus
'Compsognathus
'Muttaburrasaurus
'
'dinosaurs(2): Nanotyrannus
'
'dinosaurs(2) = "Microraptor"
'
'Psitticosaurus
'Caudipteryx
'Microraptor
'Compsognathus
'Muttaburrasaurus
'
'Remove("Microraptor")
'
'Psitticosaurus
'Caudipteryx
'Compsognathus
'Muttaburrasaurus
'
'RemoveAt(0)
'
'Caudipteryx
'Compsognathus
'Muttaburrasaurus
'
'dinosaurs.Clear()
'Count: 0

설명

Collection<T> 검색은 앞으로 첫 번째 요소부터 마지막 요소입니다.The Collection<T> is searched forward starting at the first element and ending at the last element.

기본 같음 비교자를 사용 하 여 같은지 여부를 확인 하는이 메서드가 EqualityComparer<T>.Default 에 대 한 T, 목록에서 값의 형식입니다.This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.

이 메서드는; 선형 검색을 수행합니다. 따라서 평균 실행 시간에 비례 Count합니다.This method performs a linear search; therefore, the average execution time is proportional to Count. 즉,이 메서드는 O (n) 작업, 여기서 nCount합니다.That is, this method is an O(n) operation, where n is Count.

적용 대상

추가 정보