Home »
.Net »
C# Programs
C# - Check a specified city exists in List collection using LINQ
Learn, how to check a specified city exists in the List collection using Linq in C#?
By Nidhi Last updated : April 01, 2023
Here, we will create a list using List collection that contains the name of cities then we use Linq Contains() method to check the specified city exists in the list or not.
C# program to check a specified city exists in the List collection using LINQ
The source code to check a specified city exists in the List collection using Linq, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
// C# program to check specified city exists
// in the List Collection using Linq.
using System;
using System.Collections.Generic;
using System.Linq;
class LinqDemo {
static void Main(string[] args) {
List <string> listCity = new List <string> () {
"Delhi",
"Mumbai",
"Agra",
"Gwalior",
"Jhashi"
};
string city = "Agra";
bool isExist = false;
isExist = listCity.AsEnumerable().Contains(city);
if (isExist == true)
Console.WriteLine(city + " city exists in List");
else
Console.WriteLine(city + " city does not exists in List");
}
}
Output
Agra city exists in List
Press any key to continue . . .
Explanation
In the above program, we created a class LinqDemo that contains the Main() method. In the Main() method we created a list listCity that contains the name of cities, and we also created a local variable city that is initialized with "Agra".
isExist = listCity.AsEnumerable().Contains(city);
In the above code Contains() method check the city "Agra" is exist in the list listCity. The listCity contains "Agra" that's why the Contains() method will return true and then the "Agra city exists in List" message will print on the console screen.
C# LINQ Programs »