- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
Sorting a list of integers 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'll walk you through a C# program to sort a list of integers 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 Integers Using LINQ OrderBy() Method
Let's consider an example of sorting a list of integers using the LINQ OrderBy() method.
Example
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int>() { 5, 3, 9, 1, 8, 2, 7 }; var sortedNumbers = numbers.OrderBy(n => n); Console.WriteLine("Sorted Numbers:"); foreach (var num in sortedNumbers) { Console.WriteLine(num); } } }
Output
Sorted Numbers: 12 3 5 7 8 9
In this example, we have created a List of integers named "numbers" and initialized it with some unsorted integers. 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 "sortedNumbers".
Finally, we have used a foreach loop to print the sorted list of integers 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 integers 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.