﻿ Lesson 02: Sorting a Query

Introduction to Sorting

Overview

Sorting a list consists of re-arranging its members in a certain order. The arrangement depends on the type of values of the list.

Ordering By an Expression

When you create an array or a list, you add the items in an order of your choice. When you create a select statement, the items are added to its list in the order they appear in the original list. When treating the new list or when presenting it to the user, you may want to arrange it in an order.

To support ordeing a list, the LINQ provides an operator named orderdy. To apply it, write the operator before the select operation followed by the variable used in the from clause. Here is an example:

```<!DOCTYPE html>
<html>
<title>Numbers</title>
<body>
<h1>Numbers</h1>

@{
var numbers = new int[] { 12, 45, 38, 5, 128, 525, 2448, 39, 632, 207 };

var values = from nbr in numbers
orderby nbr
select nbr;
}

<ul>
@foreach (var nbr in values)
{
<li>@nbr</li>
}
</ul>
</body>
</html>```

This would produce:

Options on Ordering a List

Arranging a List in Ascending Order

A list can be arranged in one of two directions. The default way to arrange a list of numbers is in incrementing order, which starts from the lowest to the highest value. To let you do this, the LINQ provides a keyword named ascending. To arrange a list in incrementing number, add this keyword after the name in the orderby operator. Here is an example:

```<!DOCTYPE html>
<html>
<title>Numbers</title>
<body>
<h1>Numbers</h1>

@{
var numbers = new int[] { 12, 45, 38, 5, 128, 525, 2448, 39, 632, 207 };

var values = from nbr in numbers
orderby nbr ascending
select nbr;
}

<ul>
@foreach (var nbr in values)
{
<li>@nbr</li>
}
</ul>
</body>
</html>```

In reality, if you apply the orderby operator simply followed by a variable, the list is ordered in incrementing order. This means that you can omit the ascending keyword and you will get the same result.

Sorting in Descending Order

You can arrange a list in reverse ascending order. This is referred to as descending order. To support this, the LINQ provides a keyword named descending. To use its technique, write after the name of the orderby clause. Here is an example:

```<!DOCTYPE html>
<html>
<title>Numbers</title>
<body>
<h1>Numbers</h1>

@{
var numbers = new int[] { 12, 45, 38, 5, 128, 525, 2448, 39, 632, 207 };

var values = from nbr in numbers
orderby nbr descending
select nbr;
}

<ul>
@foreach (var nbr in values)
{
<li>@nbr</li>
}
</ul>
</body>
</html>```

This would produce:

Sorting the members of a primitive-based list is quite easy. This is because the class (structures) of each data type implements the IComparable interface. This also makes it easy to sort the values of a select statement. This means that, to arrange the list of values, in the orderby statement, type the name of the from variable and use the period operator to specify the class member by which you want to arrange the list.