C# Program to Sort a List of String Names Using the LINQ OrderBy() Method
Last Updated :
06 Dec, 2021
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#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG{
static void Main( string [] args)
{
List< string > arr = new List< string >(){ "Raju" , "Avinash" ,
"Sandeep" , "Vineeth" ,
"Naveen" };
var finalres = arr.OrderBy(n => n);
Console.WriteLine( "Sorted names are:" );
foreach ( string data in finalres)
{
Console.Write(data + " " );
}
}
}
|
Output:
Sorted names are:
Avinash Naveen Raju Sandeep Vineeth
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...