C# Contains Method Explained: Use & Examples

In C#, Contains is a method used to determine if a collection or array contains a specific element. It returns a boolean value indicating whether the collection or array contains the specified element.

The Contains method can be used with various collection types such as arrays, lists, hashsets, and dictionaries. It takes one parameter indicating the element to search for, and then returns a boolean value indicating whether the element was found.

Here is an example showing how to use the Contains method to determine whether a specific element is present in an array.

int[] numbers = { 1, 2, 3, 4, 5 };
int target = 3;

bool containsTarget = numbers.Contains(target);

if (containsTarget)
{
    Console.WriteLine("数组中包含目标元素");
}
else
{
    Console.WriteLine("数组中不包含目标元素");
}

In the example above, the Contains method is used to determine if the array “numbers” includes the target element. If it does, print “The array contains the target element”; if it does not, print “The array does not contain the target element”.

Please note that the Contains method uses the default equality comparer to determine if elements are equal. If the elements in the collection are complex or custom types, you will need to implement the logic for equality comparison, or use a custom equality comparer.

bannerAds