C# Program to Sort a List of String Names Using the LINQ OrderBy() Method
Given a list of string names, now our task is to sort the names given in the list using the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. While using this method in the LINQ query you don’t need to add an extra condition to sort the list in ascending order.
Example:
Input : [ "Raj", "Amisha", "Mohan", "Mohit", "Bhuvan" ] Output : [ "Amisha", "Bhuvan", "Mohan", "Mohit", "Raj" ] Input : [ "Amu", "Amisha", "Sumita", "Gita" ] Output : [ "Amisha", "Amu", "Gita", "Sumita" ]
Approach:
1. Create and initialize a list of string types. For example arr.
2. Sorting the list(named arr) using OrderBy() method.
var finalres = arr.OrderBy(n => n);
3. Display the result using the foreach loop.
Example:
C#
// C# program to sort a list of string type // Using OrderBy() method using System; using System.Linq; using System.Collections.Generic; class GFG{ static void Main( string [] args) { // Creating and initializing list of string type List< string > arr = new List< string >(){ "Raju" , "Avinash" , "Sandeep" , "Vineeth" , "Naveen" }; // Using order by method we sort the list var finalres = arr.OrderBy(n => n); // Display the list Console.WriteLine( "Sorted names are:" ); foreach ( string data in finalres) { Console.Write(data + " " ); } } } |
Output:
Sorted names are: Avinash Naveen Raju Sandeep Vineeth