ADVERTISEMENT
ADVERTISEMENT

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

Here, we are going to learn how to sort a list of integers 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 items, and then we will print the sorted list on the console screen.

Program:

The source code to sort a list of integers 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 integers 
//using Linq OrderBy() method

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

class Demo
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>() { 49,34,13,56,25,65 };
        
        var result = list.OrderBy(num=>num);

        Console.WriteLine("Sorted list in Ascending order:");
        foreach (int value in result)
        {
            Console.Write(value + " ");
        }
        Console.WriteLine();
    }
}

Output:

Sorted list in Ascending order:
13 25 34 49 56 65
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 integer numbers.

var result = list.OrderBy(num=>num);

The above method call will return the sorted list in the ascending order.

Console.WriteLine("Sorted list in Ascending order:");
foreach (int value in result)
{
    Console.Write(value + " ");
}
Console.WriteLine();

In the above code, we accessed each integer number 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.