C# Keywords Tutorial Part 22: descending

C# Keywords Tutorial Part 22: descending

Popular programming language C# is frequently used to create games, web apps, desktop applications for Windows, and much more. Its extensive feature list makes it a potent language for programmers. One of those features enables you to sort data in descending order and is called the “descending” keyword. We’ll examine the “descending” keyword in more detail and provide some usage examples in this blog article.

In LINQ (Language Integrated Query), the “descending” keyword is used to sort a collection of data in descending sequence. To indicate the order in which the data should be sorted, it is used in conjunction with the “orderby” keyword. The syntax for using the “descending” keyword in LINQ is as follows:

var result = from x in collection
             orderby x.PropertyName descending
             select x;

In the above syntax, “x” is a variable that represents each element in the collection, “PropertyName” is the name of the property that you want to sort by, and “descending” specifies that you want to sort the data in descending order.

Here is an example of how to use the “descending” keyword in a LINQ query:

List<int> numbers = new List<int> { 5, 1, 3, 6, 2, 4 };
var descendingNumbers = from number in numbers
                        orderby number descending
                        select number;
foreach (var number in descendingNumbers)
{
    Console.WriteLine(number);
}

In the above example, we have a list of integers and we want to sort them in descending order. We use the “orderby” keyword to sort the numbers and the “descending” keyword to specify that we want to sort them in descending order. The output of the above code will be:

6
5
4
3
2
1

As you can see, the numbers are sorted in descending order from 6 to 1.

You can also use the “descending” keyword with multiple properties. Here is an example of how to use the “descending” keyword with multiple properties:

List<Student> students = new List<Student>
{
    new Student { Name = "John", Age = 22 },
    new Student { Name = "Mary", Age = 18 },
    new Student { Name = "David", Age = 24 }
};
var descendingStudents = from student in students
                         orderby student.Age descending, student.Name descending
                         select student;
foreach (var student in descendingStudents)
{
    Console.WriteLine(student.Name + " " + student.Age);
}

In the above example, we have a list of students with their names and ages. We want to sort the students in descending order by their age and then by their name. We use the “orderby” keyword with the “descending” keyword to sort the students in the desired order. The output of the above code will be:

David 24
John 22
Mary 18

As you can see, the students are sorted in descending order by their age and then by their name.

Share this post

Leave a Reply

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