C# | How to check whether a List contains a specified element
List<T>.Contains(T) Method is used to check whether an element is in the List<T> or not. Properties of List:
- It is different from the arrays. A list can be resized dynamically but arrays cannot.
- List class can accept null as a valid value for reference types and it also allows duplicate elements.
- If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
public bool Contains (T item);
Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False. Below programs illustrate the use of List<T>.Contains(T) Method: Example 1:
Time complexity: O(n) for Contains method
Auxiliary Space: O(n) where n is size of the list