C# Program to Reverse the List of Cities using LINQ


In C#, LINQ (Language Integrated Query) is a powerful feature that allows us to perform queries on various data sources, including arrays, lists, and databases. It is an efficient and concise way to manipulate data and has become an essential tool for developers. In this article, we will explore how to use LINQ to reverse a list of cities in C#.

Before we dive into the code, let us first understand what LINQ is. LINQ is a set of extensions to the .NET Framework that provides a standard way to query data from different data sources using a common syntax. It allows developers to write queries that resemble SQL statements, making it easier to manipulate data in a more readable and concise way.

Method: Using LINQ

To reverse a list of cities using LINQ, we can use the Reverse() extension method provided by LINQ. Here's how we can do it āˆ’

Example

using System.IO;
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> cities = new List<string> {"New York", "Paris", "Tokyo", "London"};
   
      var reversedCities = cities.AsEnumerable().Reverse();
   
      foreach (var city in reversedCities) {
         Console.WriteLine(city);
      }
   }
}

Output

London
Tokyo
Paris
New York

In this code, we start by initializing a list of strings named cities with four elements: "New York", "Paris", "Tokyo", and "London".

Next, we use the AsEnumerable() method to convert the list into an enumerable sequence, which can then be used with LINQ extension methods. We then use the Reverse() extension method to reverse the order of the elements in the sequence.

Finally, we use a foreach loop to iterate through the reversed sequence and print each element to the console.

Conclusion

In this article, we explored how to use LINQ to reverse a list of cities in C#. By using the Reverse() extension method provided by LINQ, we can efficiently and easily reverse the order of the elements in a list. This method is concise and readable, making it an essential tool for any C# developer.

Overall, LINQ is a powerful feature that simplifies the process of querying and manipulating data in C#. By understanding how to use LINQ, we can become more efficient programmers and develop better solutions to complex problems.

Updated on: 04-May-2023

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements