CSharp - LINQ Contains

Introduction

The Contains operator returns true if any element in the input sequence matches the specified value.

Prototypes

There are two prototypes we cover. The First Contains Prototype

public static bool Contains<T>(
  this IEnumerable<T> source,
  T value);

This prototype of Contains operator first checks the source input sequence to see whether it implements the ICollection<T> interface.

If it does, it calls the Contains method of the sequence's implementation.

If the sequence does not implement the ICollection<T> interface, it enumerates the source sequence to see whether any element matches the specified value.

Once it finds an element that does match, the enumeration stops.

The specified value is compared to each element using the EqualityComparer<K>.Default default equality comparison class.

The second prototype accepts an IEqualityComparer<T> object and each element in the sequence is compared to the passed value using the passed equality comparison object.

public static bool Contains<T>(
  this IEnumerable<T> source,
  T value,
  IEqualityComparer<T> comparer);

Exceptions

ArgumentNullException is thrown if the source input sequence is null.

The following code uses a value that we know is not in our input sequence,

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   ww w  .  j  a v  a 2 s .  com
{
    static void Main(string[] args)
    {
         string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};

         bool contains = codeNames.Contains("Ruby");
         Console.WriteLine(contains);

    
         contains = codeNames.Contains("Oracle");
         Console.WriteLine(contains);
    }
}

Result

Related Topics