[LINQ Operators] Contains

The “Contains” operator checks whether a sequence contains a given element. It returns a boolean value (true/false). Moreover, you can provide the custom comparer “IEqualityComparer<T>”.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “Contains” operator

  • NonDeferred operator
  • Purpose: Quantifier

 

3. Prototypes

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

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

The “Contains()” operator returns “true” if any element in the source sequence matches the specified value.

 

4. Example 1 (Standard Operator)

IEnumerable<Employee> emps = Employee.GetEmployees();

Employee janeSmith =
  new Employee { ID = 2, Name = "Jane Smith", CityID = 2 };
bool isThere = emps.Contains(janeSmith);
if (isThere)
  Console.WriteLine("Jane Smith is in the list");
else
  Console.WriteLine("Jane Smith is not in the list");

The result is surprisingly (?) “false”. Even though the object has the exactly the same state, it is a brand-new object.

IEnumerable<Employee> emps = Employee.GetEmployees();

Employee janeSmith =
  emps.SingleOrDefault(e => e.Name == "Jane Smith");
bool isThere = emps.Contains(janeSmith);
if (isThere)
  Console.WriteLine("Jane Smith is in the list");
else
  Console.WriteLine("Jane Smith is not in the list");

Now you get the object directly from the list and the result is “true”.

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Contains()” operator.

 

6. Example 1 (Standard Operator)  – with a custom comparer

public class MyNameComparer : IEqualityComparer<Employee>
{
  public bool Equals(Employee x, Employee y)
  {
    return x.Name.Equals(y.Name,
      StringComparison.InvariantCultureIgnoreCase);
  }
  public int GetHashCode(Employee obj)
  {
    return obj.Name.GetHashCode();
  }
}

You can pass the custom Comparer as the second argument of the “Contains()” operator.

IEnumerable<Employee> emps = Employee.GetEmployees();
MyNameComparer compare = new MyNameComparer();

Employee janeSmith =
  new Employee { ID = 2, Name = "Jane Smith", CityID = 2 };
bool isThere = emps.Contains(janeSmith, compare);
if (isThere)
  Console.WriteLine("Jane Smith is in the list");
else
  Console.WriteLine("Jane Smith is not in the list");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s