C# | Searching the index of specified object in Collection<T>
Collection<T>.IndexOf(T) method is used to search for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>.
Syntax:
public int IndexOf (T item);
Here, item is the object to locate in the List<T>. The value can be null for reference types.
Return Value: This method returns the zero-based index of the first occurrence of item within the entire Collection<T>, if found, otherwise, -1.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< string > myColl = new Collection< string >();
myColl.Add( "A" );
myColl.Add( "B" );
myColl.Add( "C" );
myColl.Add( "D" );
myColl.Add( "D" );
myColl.Add( "E" );
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
Console.WriteLine( "Index : " + myColl.IndexOf( "D" ));
}
}
|
Output:
A
B
C
D
D
E
Index : 3
Example 2:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< int > myColl = new Collection< int >();
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
Console.WriteLine( "Index : " + myColl.IndexOf(7));
}
}
|
Output:
2
3
4
5
Index : -1
Note:
- The Collection<T> is searched forward starting at the first element and ending at the last element.
- This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.
- This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...