0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ Contains in C# - Simple Guide

Use Contains in LINQ to check if a collection has a specific item by calling collection.Contains(item). It returns true if the item exists, otherwise false. This works with lists, arrays, and other enumerable types.
📐

Syntax

The basic syntax of LINQ Contains is:

  • collection.Contains(item) - checks if item exists in collection.
  • collection can be any enumerable like an array, list, or other LINQ-supported collections.
  • Returns a bool: true if found, false if not.
csharp
bool result = collection.Contains(item);
💻

Example

This example shows how to use Contains to check if a list of strings contains a specific word.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string> { "apple", "banana", "cherry" };
        bool hasBanana = fruits.Contains("banana");
        bool hasOrange = fruits.Contains("orange");

        Console.WriteLine($"Contains banana? {hasBanana}");
        Console.WriteLine($"Contains orange? {hasOrange}");
    }
}
Output
Contains banana? True Contains orange? False
⚠️

Common Pitfalls

Common mistakes when using Contains include:

  • Using Contains on a collection of complex objects without overriding Equals and GetHashCode, which causes unexpected false results.
  • Case sensitivity issues when checking strings, since Contains is case-sensitive by default.
  • Confusing Contains with string method Contains which checks substrings, not collection membership.

Example of case sensitivity issue and fix:

csharp
var fruits = new List<string> { "Apple", "Banana", "Cherry" };

// Case-sensitive check (will be false)
bool hasApple = fruits.Contains("apple");

// Case-insensitive check using LINQ Any
bool hasAppleIgnoreCase = fruits.Any(f => f.Equals("apple", StringComparison.OrdinalIgnoreCase));
📊

Quick Reference

  • Purpose: Check if a collection contains an element.
  • Return type: bool
  • Case sensitivity: Yes, for strings.
  • Works with: Arrays, Lists, IEnumerable<T>.
  • Use with complex types: Override Equals and GetHashCode.

Key Takeaways

Use Contains to check if a collection has a specific item, returning true or false.
Remember Contains is case-sensitive for strings by default.
For complex objects, override Equals and GetHashCode to get correct results.
Use Any with a custom comparison for case-insensitive string checks.
Contains works on arrays, lists, and any enumerable collection.