The source code to sort a list of string names using the Linq OrderBy() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to sort a list of string names
//using the Linq OrderBy() method.
using System;
using System.Linq;
using System.Collections.Generic;
class Demo
{
static void Main(string[] args)
{
List<string> list = new List<string>() {"Andy", "Gren", "Steve","Arun","Brock"};
var result = list.OrderBy(name=>name);
Console.WriteLine("Names in sorted order:");
foreach (string name in result)
{
Console.Write(name + " ");
}
Console.WriteLine();
}
}
Output:
Names in sorted order:
Andy Arun Brock Gren Steve
Press any key to continue . . .
Explanation:
In the above program, we created a class Demo that contains the Main() method. In the Main() method we created a list that contains unordered string names.
var result = list.OrderBy(name=>name);
The above method call will return the sorted list in the ascending order.
Console.WriteLine("Names in sorted order:");
foreach (string name in result)
{
Console.Write(name + " ");
}
Console.WriteLine();
In the above code, we accessed each name one by one and print it on the console screen.
Program:
The source code to sort a list of string names using the Linq OrderBy() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class Demo that contains the Main() method. In the Main() method we created a list that contains unordered string names.
The above method call will return the sorted list in the ascending order.
In the above code, we accessed each name one by one and print it on the console screen.