Linq Contains in C#

LINQ (Language Integrated Query) is a powerful language feature in C# that allows you to query data from different sources such as arrays, lists, databases, and XML documents. One of the most commonly used LINQ operators is Contains, which allows you to search for specific values in a collection. In this lesson, we will learn how to use Contains in C#.

Let’s assume we have a collection of strings that contain the names of different countries. We want to search for all the countries that contain the word “land”. To achieve this, we can use the Contains operator.

Here’s the code to achieve this:
var countries = new List<string> { "Finland", "Iceland", "Netherlands", "Switzerland", "New Zealand" };

var searchedCountries = countries.Where(country => country.Contains("land"));

foreach (var country in searchedCountries)
{
    Console.WriteLine(country);
}

In the above code, we first create a list of strings that contain the names of different countries. We then use the Where method along with the Contains operator to filter out all the countries that contain the word “land”. This returns a new collection of strings that contain only the countries that match the search criteria.

We then iterate through the searchedCountries collection and print the name of each country.

The output of the above code would be:
Finland
Netherlands
Switzerland
New Zealand

As we can see, the Contains operator has filtered out all the countries that do not contain the word “land”, and we are left with a collection that only contains the countries that match the search criteria.

In conclusion, LINQ Contains in C# is a powerful feature that allows you to search for specific values in a collection. By using this feature, you can easily filter out the data that does not match your search criteria and extract meaningful insights from your data.