C# Keywords Tutorial Part 4: ascending

C# Keywords Tutorial Part 4: ascending

C# is a strong programming language with a variety of features that aid programmers in creating orderly, effective code. The word ascending, which is used to sort data in ascending order, is one of these properties. We will discuss the ascending keyword in C# and give usage examples in this blog article.

What is the ascending keyword in C#?

Data is sorted in ascending order using the ascending keyword. To specify the order in which data should be sorted, it is used in conjunction with the orderby keyword. Data is sorted either in ascending or descending order using the ascending and descending keywords, respectively.

Syntax of the ascending keyword

The syntax for using the?ascending?keyword is as follows:

orderby variable_name ascending        

In this syntax,?variable_name?is the name of the variable that contains the data to be sorted.

Examples of using the ascending keyword in C#

Let’s take a look at some examples of how the?ascending?keyword can be used in C#.

Example 1: Sorting an array of integers in ascending order

In this example, we have an array of integers that we want to sort in ascending order.

int[] numbers = { 5, 3, 8, 1, 7, 2 };
var sortedNumbers = from n in numbers
? ? ? ? ? ? ? ? ? ? orderby n ascending
? ? ? ? ? ? ? ? ? ? select n;
foreach (var number in sortedNumbers)
{
? ? Console.WriteLine(number);
}        

The output of this code will be:

1
2
3
5
7
8        

Example 2: Sorting a list of strings in ascending order

In this example, we have a list of strings that we want to sort in ascending order.

List<string> fruits = new List<string> { "apple", "banana", "orange", "kiwi", "pear" };
var sortedFruits = from f in fruits
? ? ? ? ? ? ? ? ? ?orderby f ascending
? ? ? ? ? ? ? ? ? ?select f;
foreach (var fruit in sortedFruits)
{
? ? Console.WriteLine(fruit);
}        

The output of this code will be:

apple
banana
kiwi
orange
pear        

Example 3: Sorting a collection of custom objects in ascending order

In this example, we have a collection of custom objects that we want to sort in ascending order based on a property of the object.

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


List<Person> people = new List<Person>?
{
? ? new Person { Name = "Alice", Age = 25 },
? ? new Person { Name = "Bob", Age = 30 },
? ? new Person { Name = "Charlie", Age = 20 }
};


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


foreach (var person in sortedPeople)
{
? ? Console.WriteLine($"{person.Name} ({person.Age})");
}        

The output of this code will be:

Charlie (20)
Alice (25)
Bob (30)        

要查看或添加评论,请登录

社区洞察

其他会员也浏览了