C# - Example of LINQ OrderBy() Method | Sort a List of Strings

Learn, how to sort a list of string names using the Linq OrderBy() method in C#? By Nidhi Last updated : April 01, 2023

Here we will use Linq OrderBy() method of List. The list contains unordered names, and then we will print the sorted list of names on the console screen.

C# program to sort a list of strings using the LINQ OrderBy() method

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.

C# LINQ Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.