Usage of C# (C Sharp) Query Keywords – orderby, ascending, descending

This article will guide you in understanding the purpose of orderby, ascending and descending query keywords and how can it be used in LINQ Query Expression.

Hope you are familiar with the order by clause of SQL Query. Similar logic is incorporated in the orderby keyword of C#. You can order your query results based on a specific key field in either ascending or descending order. Not just one key field, you can sort the result based on as many key fields as you require. Consider the following example:

class sampleClass {
static void Main() {
int[] sampleArray = { 12, 125, 53, 25, 165, 21, 280 };
IEnumerable<int> query1 = from arrayVal in sampleArray
where arrayVal % 2 !=0
orderby arrayVal ascending
select arrayVal;
IEnumerable<int> query2 = from arrayVal in sampleArray
where arrayVal % 2 !=0
orderby arrayVal descending
select arrayVal;
IEnumerable<int> query3 = from arrayVal in sampleArray
where arrayVal % 2 !=0
orderby arrayVal
select arrayVal;
Console.WriteLine(“Result of query1 is:”);
foreach (int resultVal in query1)
{
Console.Write(resultVal+” “);
}
Console.WriteLine(“Result of query1 is:”);
foreach (int resultVal in query1)
{
Console.Write(resultVal+” “);
}
Console.WriteLine(“Result of query1 is:”);
foreach (int resultVal in query1)
{
Console.Write(resultVal+” “);
}
}
}

This example illustrates the purpose of three query keywords namely orderby, ascending and descending. You have an integer array called sampleArray. Its elements are in random order. You want to fetch odd elements from the array and display them in a particular order. For sorting the elements, you use the orderby keyword.

You can sort the array elements in either ascending or descending order. Query named query1 has the elements sorted in ascending order. Query named query2 has the elements sorted in descending order. How about query3? Neither ascending nor descending keyword is mentioned. Therefore the elements will be sorted in ascending order by default. It means that query1 and query3 are equivalent and they produce the same result. Output of the above code will be:


Result of query1 is: 21 25 53 125 165
Result of query2 is: 165 125 53 25 21
Result of query3 is: 21 25 53 125 165

The above example sorts the result by specifying one key field in orderby clause. You can also specify more than one key field and each of it can have a different order i.e. you can sort records based on key field1 in ascending order and key field2 in descending order. Both criteria can be mentioned in the same orderby clause. This is illustrated in the following example:

class sampleClass {
public class employee {
public int empId { get; set; }
public string empName { get; set; }
}
public static List<employee> accessEmployeeRecords() {
List< employee> emp = new List<employee> {
new employee {empId=123, empName="Alphonse"},
new employee {empId=121, empName="Michael"},
new employee {empId=122, empName="Rose"},
};
return emp;
}
static void Main(string[] args) {
List<employee> emp = accessEmployeeRecords();
IEnumerable<employee> sortQuery =from empRec in emp
orderby empRec.empId ascending, empRec.empName descending
select empRec;
Console.WriteLine("Sorted Employee Records are mentioned below:");
foreach (employee empRec in sortQuery) {
Console.WriteLine(empRec.empId + " " + empRec.empName);
}
}
}

In the earlier example, data source you used is an array. But in this example, you have used a class as the data source and manipulated the query over class instances. You have a class called employee containing empId and empName of each employee. You create a list of employees and sort them based on their empId (in ascending order) and empName (in descending order).

In both the examples dealt, you are sorting the records based on a field which belongs to the object on which query is built. But it is not always necessary. Moreover you can sort the result in a random order instead of ascending or descending order. In the following example, the Main() method of earlier example is modified to display employee records in random order:

static void Main(string[] args) {
Random randomVar = new Random( );
List<employee> emp = accessEmployeeRecords();
IEnumerable<employee> sortQuery =from empRec in emp
orderby randomVar.Next()
select empRec;
Console.WriteLine("Employee Records Sorted in Random Order are mentioned below:");
foreach (employee empRec in sortQuery) {
Console.WriteLine(empRec.empId + " " + empRec.empName);
}
}

This example will output the employee records in a random order. Each time you execute the code, you might get different output.

|How to Define Custom Error Pages for Error Handling In ASP.Net Application| Role of Web gardens and web farms in ASP.NET | Understanding Purpose and Usage of "event" Class Member Modifier in C# (C Sharp) | Understanding the Structure and Content of Web.Config File | Usage of C# (C Sharp) Query Keywords – group, by, into | Usage of C# (C Sharp) Query Keywords – join, on, equals, let |Usage of C# (C Sharp) Query Keywords – orderby, ascending, descending | Usage of C# (C Sharp) Query Keywords – select, from, where, in | Usage of Lambda Operator (=>) in C# (C Sharp) |Using C# (C Sharp) as a tool for object oriented programming | Using Dictionaries in .Net – An Overview | Using WCF for providing web service |

 


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.