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 ifitemexists incollection.collectioncan be any enumerable like an array, list, or other LINQ-supported collections.- Returns a
bool:trueif found,falseif 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
Containson a collection of complex objects without overridingEqualsandGetHashCode, which causes unexpectedfalseresults. - Case sensitivity issues when checking strings, since
Containsis case-sensitive by default. - Confusing
Containswith string methodContainswhich 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
EqualsandGetHashCode.
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.