C# Keywords Tutorial Part 60: orderby

C# Keywords Tutorial Part 60: orderby

C# is a versatile programming language that provides a variety of features and functionalities to developers. One such feature is the “orderby” keyword, which allows sorting of data in ascending or descending order. In this blog post, we’ll explore the “orderby” keyword in C# and provide some code examples to illustrate its usage.

Introduction to “orderby”

To sort data in C#, use the “orderby” keyword. To specify the sorting order, it is used with the “ascending” and “descending” keywords. Developers that know how to utilize the “orderby” keyword effectively may use it to swiftly sort and arrange massive volumes of data.

Using “orderby” in C#

The “orderby” keyword is used in LINQ (Language Integrated Query) statements, which allow developers to query and manipulate data in C#. Here’s a basic example of how to use “orderby” in a LINQ statement:

var numbers = new List<int> { 5, 2, 8, 3, 9, 1, 4, 6, 7 };

var sortedNumbers = from n in numbers
                    orderby n ascending
                    select n;

In this example, we have a list of numbers that we want to sort in ascending order. We use the “orderby” keyword to specify that we want to sort by the value of each number, and we use the “ascending” keyword to indicate that we want to sort the numbers in ascending order. The “select” keyword is used to select the sorted numbers from the list.

Here’s another example, this time sorting a list of objects:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var people = new List<Person>
{
    new Person { Name = "John", Age = 25 },
    new Person { Name = "Jane", Age = 32 },
    new Person { Name = "Mary", Age = 18 },
    new Person { Name = "Steve", Age = 45 }
};

var sortedPeople = from p in people
                   orderby p.Age descending
                   select p;

In this example, we have a list of Person objects that we want to sort by age in descending order. We use the “orderby” keyword to specify that we want to sort by the “Age” property of each Person object, and we use the “descending” keyword to indicate that we want to sort the people in descending order.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *