C# Program to Sort a List of String Names Using the LINQ OrderBy() Method


Sorting a list of string names is a common task in programming, and the LINQ OrderBy() method in C# provides an easy and efficient way to do so. In this article, we will walk you through a C# program to sort a list of string names using the LINQ OrderBy() method.

What is LINQ OrderBy() Method?

The LINQ OrderBy() method is used to sort the elements of a sequence in ascending or descending order based on one or more keys. The keys can be simple properties or complex expressions that return a value based on one or more properties of the objects in the sequence.

Syntax of the OrderBy() Method

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
   this IEnumerable<TSource> source,
   Func<TSource, TKey> keySelector
)

The first parameter is the source sequence to be sorted, and the second parameter is a function that returns the key to be used for sorting each element. The returned value is an ordered sequence of the same type as the source sequence.

Sorting a List of String Names Using LINQ OrderBy() Method

Let's consider an example of sorting a list of string names using the LINQ OrderBy() method.

Example

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> names = new List<string>() { "John", "Alice", "Peter", "Bob", "Mary" };
   
      var sortedNames = names.OrderBy(n => n);
   
      Console.WriteLine("Sorted Names:");
      foreach (var name in sortedNames) {
         Console.WriteLine(name);
      }
   }
}

Output

Sorted Names:
Alice
Bob
John
Mary
Peter

In this example, we have created a List of string names named "names" and initialized it with some unsorted string names. Then, we have used the OrderBy() method to sort the list in ascending order based on each element's value.

The lambda expression n => n is used as the key selector function, which simply returns the value of each element. The sorted list is stored in a new variable named "sortedNames".

Finally, we have used a foreach loop to print the sorted list of string names to the console.

Conclusion

The LINQ OrderBy() method in C# is a powerful tool for sorting a sequence of elements based on one or more keys. In this article, we have shown how to use the OrderBy() method to sort a list of string names in ascending order using a lambda expression as the key selector. This is just the tip of the iceberg when it comes to the capabilities of LINQ and C#. By mastering LINQ, you can simplify and streamline your code, making it more efficient and easier to maintain.

Updated on: 04-May-2023

943 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements