Usage of C# (C Sharp) Query Keywords orderby, ascending, descendingThis 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
{ 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:
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
{ 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) { This example will output the employee records in a random order. Each time you execute the code, you might get different output.
|