Skip to content
Related Articles
Open in App
Not now

Related Articles

C# Program to Reverse the List of Cities using LINQ

Improve Article
Save Article
  • Last Updated : 09 Dec, 2021
Improve Article
Save Article

Given a list of city names, we need to reverse the list of cities and this can be done using the reverse() method in LINQ. The Reverse() method reverses the sequence of the elements in the specified list. it is available in both Queryable and Enumerable classes. It will return an ArgumentNullException if the given source is null.

Syntax:

public static void Reverse ();

Example:

Input  : ["mumbai", "pune", "bangalore", "hyderabad"]
Output : ["hyderabad", "bangalore", "pune", "mumbai"] 

Input  : ["chennai", "vizag", "delhi"]
Output : ["delhi", "vizag", "chennai"]

Approach:

  • A list of cities is defined using arrayList.
  • The list of cities is reverse using the Reverse() method.
cities.Reverse();
  • Finally resultant array is printed using the foreach loop.
foreach (var city in cities)
{
    Console.Write(city + " ");
}

C#




using System;
using System.Linq;
using System.Collections.Generic;
  
class geek
{
    static void Main(string[] args)
    {
        List<string> cities = new List<string>() {"mumbai","hyderabad","pune","bangalore"};
        // reversing the cities arrayList
        cities.Reverse();
  
        Console.Write("The Reversed list = ");
        Console.Write("[ ");
        foreach (var city in cities)
        {
            Console.Write(city + " ");
        }
        Console.Write(" ]");
    }
}


Output

The Reversed list = [ bangalore pune hyderabad mumbai  ]
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!