Enumerable.Contains Method

Namespace: System.Linq

Summary

Checks whether a sequence contains a specified element, using a specified comparer.

Syntax

public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource>? comparer)
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)

Parameters

Parameter Description
source An IEnumerable<TSource> to check for a condition.
value The value to locate in the sequence.
comparer An IEqualityComparer<TSource> to compare elements.

Returns

true if the source sequence contains an element that has the specified value; otherwise, false.

Exceptions

Exception Type Condition
ArgumentNullException source is null.

Remarks

The Contains extension method performs a linear search. It iterates through the elements of the sequence until it finds an element equal to the specified value. If the sequence does not contain the specified element, it returns false.

The version of Contains that takes an IEqualityComparer<TSource> allows you to specify a custom comparer for comparing elements. If no comparer is specified, the default equality comparer for the type TSource is used.

Examples

Example 1: Basic Usage

// C# Example
using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        List fruits = new List { "apple", "banana", "cherry", "date" };

        string fruitToCheck1 = "banana";
        bool containsFruit1 = fruits.Contains(fruitToCheck1);
        Console.WriteLine($""Does the list contain '{fruitToCheck1}'? {containsFruit1}""); // Output: True

        string fruitToCheck2 = "grape";
        bool containsFruit2 = fruits.Contains(fruitToCheck2);
        Console.WriteLine($""Does the list contain '{fruitToCheck2}'? {containsFruit2}""); // Output: False
    }
}

Example 2: Using a Custom Comparer

// C# Example
using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        List words = new List { "Apple", "Banana", "Cherry", "Date" };

        string wordToCheck = "apple";
        // Case-insensitive comparison
        bool containsWord = words.Contains(wordToCheck, StringComparer.OrdinalIgnoreCase);
        Console.WriteLine($""Does the list contain '{wordToCheck}' (case-insensitive)? {containsWord}""); // Output: True
    }
}

See Also