What is the purpose of the "orderby" clause in LINQ?
The OrderBy
clause in LINQ serves the purpose of sorting elements in a collection or sequence based on one or more specified criteria. It allows you to arrange data in a specific order, such as ascending or descending, making it easier to retrieve, display, or analyze the information in an organized manner.
Syntax: 'orderby keyExpression [ascending/descending]'
-
keyExpression
: Specifies the expression or property based on which the elements should be sorted.
-
ascending/descending
(optional): Indicates the sorting order. If not specified, the default order is ascending.
Here's a complete source code example to illustrate the usage of the OrderBy
clause along with its output:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Define a class for Student
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
// Create a list of students
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Age = 20 },
new Student { Name = "Bob", Age = 22 },
new Student { Name = "Charlie", Age = 18 },
new Student { Name = "David", Age = 25 },
};
// Use LINQ to order students by age in ascending order
var orderedStudents = students.OrderBy(student => student.Age);
// Display the ordered list of students
Console.WriteLine("Ordered list of students by age (ascending):");
foreach (var student in orderedStudents)
{
Console.WriteLine($"Name: {student.Name}, Age: {student.Age}");
}
}
}
Output:
Ordered list of students by age (ascending):
Name: Charlie, Age: 18
Name: Alice, Age: 20
Name: Bob, Age: 22
Name: David, Age: 25
In this example, we define a Student class with properties for Name
and Age
. We create a list of Student
objects called students
. Using the OrderBy
clause in LINQ, we order these students by their ages in ascending order.
The result is an ordered sequence of students, and we display the list in ascending order of age. This demonstrates how the OrderBy
clause is used to sort data based on specific criteria, making it easier to work with data in a structured and organized fashion.
The OrderBy
clause allows you to order the elements of a sequence based on specific criteria, providing control over the arrangement of data. It enables you to retrieve sorted results that can be more meaningful and useful for further processing or presentation.