C# program to check a specified city exists in the List collection using Linq

Here, we are going to learn how to check a specified city exists in the List collection using Linq in C#?
Submitted by Nidhi, on September 03, 2020

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.


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");
            Console.WriteLine(city + " city does not exists in List");


Agra city exists in List
Press any key to continue . . .


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 »


What's New (MCQs)

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.