ADVERTISEMENT
ADVERTISEMENT

C# program to sort a list of string names using the Linq OrderBy() method

Here, we are going to learn how to sort a list of string names using the Linq OrderBy() method in C#?
Submitted by Nidhi, on August 29, 2020

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.

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.

//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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.