CSharp - LINQ Contains


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


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);


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,


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

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

         contains = codeNames.Contains("Oracle");


Related Topics