Summary: in this tutorial, you’ll learn how to use the LINQ Contains() method to check if a sequence contains a specific element.
Introduction to the LINQ Contains() method
The Contains() is a LINQ extension method that returns true if a sequence contains an element:
bool Contains<TSource>(
this IEnumerable<TSource> source,
TSource value
);Code language: C# (cs)In this syntax:
TSourceis the type of element in thesourcesequence.sourceis the input sequence with theIEnumerable<T>type.valueis the element to locate in the source sequence.
The Contains() method returns true if the source sequence contains the element value or false otherwise.
Once the Contains() find the value in the source sequence, it stops enumerating the sequence immediately.
The Contains() uses a default equality comparer to compare the value with the elements in the source sequence.
The Contains() method is available for all collections that implement the IEnumerable<T> interface including List<T>.
If you want to use a custom equality comparer, you can use the following method overload:
bool Contains<TSource>(
this IEnumerable<TSource> source,
TSource value,
IEqualityComparer<TSource>? comparer
);Code language: C# (cs)In this syntax, you can pass a custom equality comparer to the third parameter of the Contains() method to compare the value with the elements of the source sequence.
LINQ Contains() examples
Let’s take some examples of using the LINQ Contains() method.
1) Using the LINQ Contains() to check if an array contains a value
The following program demonstrates how to use the LINQ Contains() method to check if an array contains a specific integer:
using static System.Console;
int[] numbers = { 1, 2, 3, 4, 5 };
bool containsThree = numbers.Contains(3);
bool containsTen = numbers.Contains(10);
WriteLine(containsThree); // true
WriteLine(containsTen); // falseCode language: C# (cs)In this example, we use the Contains() method to check if the numbers array contains the integers 3 and 10 respectively.
The method returns true for 3 because it is present in the array and false for 10 because it is not available in the array.
2) Using the LINQ Contains() to check if a list contains a value
The following program illustrates how to use the LINQ Contains() method to check if a list of strings contains a string:
using static System.Console;
List<string> fruits = new(){
"apple",
"banana",
"cherry",
"strawberries"
};
bool containsCherry = fruits.Contains("cherry");
bool containsMango = fruits.Contains("mango");
WriteLine(containsCherry);// true
WriteLine(containsMango);// falseCode language: C# (cs)In this example, we use the Contains() method to check if the fruits list contains the string cherry and mango respectively.
The method returns true for cherry because cherry is present in the list while it returns false for mango because mango is not in the list.
3) Using the LINQ Contains() method that use a custom equality comparer
The following example demonstrates how to use the LINQ Contains() method to check if a person is in the list of Person objects using a custom equality comparer:
// Define a custom Person class
class Person
{
public string? SSN { get; set; }
public string? Name { get; set; }
}
// Define a custom PersonComparer class that compares
// Person objects based on their SSN
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person? x, Person? y)
{
// Check for null values
if (x == null || y == null)
return false;
// Check if the two Person objects are the same reference
if (ReferenceEquals(x, y))
return true;
// Compare the SSN of the two Person objects
// to determine if they're the same
return x.SSN == y.SSN;
}
public int GetHashCode(Person? obj)
{
if (obj == null || obj.SSN == null)
return 0;
// Use the SSN of the Person object
// as the hash code
return obj.SSN.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
// Create a List of Person objects
List<Person> people = new List<Person> {
new Person { SSN = "123-45-6789", Name = "John Smith" },
new Person { SSN = "987-65-4321", Name = "Jane Doe" },
new Person { SSN = "555-55-5555", Name = "Bob Johnson" }
};
// Create a Person object to check if it's present in the List
Person person = new() { SSN = "123-45-6789", Name = "John Smith" };
// Check if the List contains the Person object using a custom comparer
bool containsPerson = people.Contains(person, new PersonComparer());
if (containsPerson)
{
Console.WriteLine($"{person.Name} is present in the list of people.");
}
else
{
Console.WriteLine($"{person.Name} is not present in the list of people.");
}
Console.ReadLine();
}
}
Code language: C# (cs)Output:
John Smith is present in the list of people.Code language: C# (cs)How it works.
First, define a Person class that has two properties: Social Security Number (SSN) and Name:
class Person
{
public string? SSN { get; set; }
public string? Name { get; set; }
}Code language: C# (cs)Second, define a custom PersonComparer class that compares two Person objects based on their SSN:
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person? x, Person? y)
{
// Check for null values
if (x == null || y == null)
return false;
// Check if the two Person objects are the same reference
if (ReferenceEquals(x, y))
return true;
// Compare the SSN of the two Person objects
// to determine if they're the same
return x.SSN == y.SSN;
}
public int GetHashCode(Person? obj)
{
if (obj == null || obj.SSN == null)
return 0;
// Use the SSN of the Person object
// as the hash code
return obj.SSN.GetHashCode();
}
}Code language: C# (cs)Third, create a list that contains three Person objects and a person object to locate in the list. The Contains() method checks if the list contains the person object using the PersonComparer that compares two person objects by their . The method returns SSNtrue because the person object with the name John Smith and SSN"123-45-5555" is in the list:
class Program
{
static void Main(string[] args)
{
// Create a List of Person objects
List<Person> people = new List<Person> {
new Person { SSN = "123-45-6789", Name = "John Smith" },
new Person { SSN = "987-65-4321", Name = "Jane Doe" },
new Person { SSN = "555-55-5555", Name = "Bob Johnson" }
};
// Create a Person object to check if it's present in the List
Person person = new() { SSN = "123-45-6789", Name = "John Smith" };
// Check if the List contains the Person object using a custom comparer
bool containsPerson = people.Contains(person, new PersonComparer());
if (containsPerson)
{
Console.WriteLine($"{person.Name} is present in the list of people.");
}
else
{
Console.WriteLine($"{person.Name} is not present in the list of people.");
}
Console.ReadLine();
}
}
Code language: C# (cs)Summary
- Use the
Contains()method to check if a sequence contains an element using an equality comparer.