C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
Last Updated :
23 Jul, 2025
Given a list of integers, now our task is to sort the given list of integers. So we use the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. This method is overloaded in two different ways:
- OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>): It is used to sort the items of the given sequence in ascending order according to the key and performs a stable sort on the given sequence or list.
- OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>): It is used to sort the items of the given sequence in ascending order by using a given comparer and also performs a stable sort on the given sequence.
Example:
Input : [90, 87, 34, 23, 22, 56, 21, 89]
Output : [21, 22, 23, 34, 56, 87, 89, 90]
Input : [10, 11, 2, 3, 18, 5,]
Output : [2, 3, 5, 10, 11, 18]
Approach:
1. Create and initialize a list of integer types. For example nums.
2. Sorting the list(named nums) using OrderBy() method
var result_set = nums.OrderBy(num => num);
3. Display the result using the foreach loop.
Example:
C#
// C# program to sort a list of integers
// Using OrderBy() method
using System;
using System.Linq;
using System.Collections.Generic;
class GFG{
static void Main(string[] args)
{
// Creating and initializing list of integers
List<int> nums = new List<int>() { 50, 20, 40, 60, 33, 70 };
// Using order by method we sort the list
var result_set = nums.OrderBy(num => num);
// Display the list
Console.WriteLine("Sorted in Ascending order:");
foreach (int value in result_set)
{
Console.Write(value + " ");
}
}
}
OutputSorted in Ascending order:
20 33 40 50 60 70
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers