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

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

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

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 »




Comments and Discussions!

Load comments ↻





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