C# | Check if an element is in the Collection<T>
Collection<T>.Contains(T) method is used to determine whether an element is in the Collection<T>.
Syntax:
public bool Contains (T item);
Here, item is the object to locate in the Collection<T>. The value can be null for reference types.
Return Value: This method return True if item is found in the Collection<T>, otherwise, False.
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( "E" );
Console.WriteLine(myColl.Contains( "A" ));
}
}
|
Output:
True
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);
Console.WriteLine(myColl.Contains(6));
}
}
|
Output:
False
Note: 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...