How to reverse a C# List

C# List<T> class provides methods and properties to create a list of objects (classes). You can add items to a list during the initialization or using List.Add() and List.AddRange() methods.
 
List is a generic class. You must import the following namespace before using the List<T> class.
 
using System.Collections.Generic;
 
The Reverse method of List<T> reverses the order all items in in the List.
The following code example reverses a List.
  1. // List of string  
  2. List<string> authors = new List<string>(5);  
  3. authors.Add("Mahesh Chand");  
  4. authors.Add("Chris Love");  
  5. authors.Add("Allen O'neill");  
  6. authors.Add("Naveen Sharma");  
  7. authors.Add("Mahesh Chand");  
  8. authors.Add("Monica Rathbun");  
  9. authors.Add("David McCarter");  
  10.   
  11. Console.WriteLine("Original List items");  
  12. Console.WriteLine("===============");  
  13. // Print original order  
  14. foreach (string a in authors)  
  15. Console.WriteLine(a);  
  16.   
  17. // Reverse list items  
  18. authors.Reverse();  
  19.   
  20. Console.WriteLine();  
  21. Console.WriteLine("Sorted List items");  
  22. Console.WriteLine("===============");  
  23. // Print reversed items  
  24. foreach (string a in authors)  
  25. Console.WriteLine(a);  
Listing 1.
The output of Listing 8 looks like Figure 1.
 
Reverse C# List 
 
Figure 1.
 
 
 



Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.