C# Program to Check a Specified City Exists in the List Collection using LINQ
Given a list, we need to check if a specified city exists in the given list using LINQ. So we can do this task using contains() method. This method is used to check whether a sequence contains a specified element or not. The method overloads in the following ways:
- Contains<TSource>(IEnumerable<TSource>, TSource): It is used to check whether the specified sequence or list holds the given element by using the default equality comparer.
- Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>): It is used to check whether the specified sequence or list holds the given element by using a specified IEqualityComparer<T>.
public static bool Contains<TSource> (this System.Collections.Generic.IEnumerable<TSource> Mylist, TSource element);
Return Type: The return type is Boolean. It will return true if the given element is present in the list. Otherwise, it will return false.
Input : ["Mumbai", "Pune", "Bangalore", "Hyderabad"] search_city : "Mumbai" Output : True Input : ["Chennai", "Vizag", "Delhi"] search_city : "Hyderabad" Output : False
- Create a method isPresent() that takes city list and name of the city to be searched as arguments.
- In isPresent() method, Using contains() check if the city is present in list or not.bool isExist = City_List.AsEnumerable().Contains(city);
If the city is present it will return true, else it will return false. By using an if condition check if it is true or false and print the result.
- In main method, create a list of city names using arrayList.
- Calling isPresent() method with two parameters one is list and another one is the name of city that we want to check is present or not.isPresent(City_List, "Mumbai");
Mumbai is present in list Chennai is not present in list
Explanation: In the above example, first of all, we create an isPresent() method. In this method, we use contains() method to check if the city is present in the list or not and store the result in isExist variable. Now when the if statement is true then it will return “City_name is present in the list” otherwise return “City_name is not present in the list”. Now in the main method, we create a list that contains city names and then call isPresent() method with the city list and name of the city, that is isPresent(City_List, “Mumbai”); and isPresent(City_List, “Chennai”);. As the 1st specified city name is Mumbai and it is present in the list so it returned true, the second specified city name is Chennai which is not there in the list so it returned false.