InterviewSolution
Saved Bookmarks
| 1. |
What is the typical usage of OrderBy clause in C#? |
|
Answer» The OrderBy clause in C# allows the elements in the COLLECTION to be sorted in ascending order or DESCENDING order as required based on specified fields. Also multiple keys can be specified to make more secondary sort OPERATIONS if they are required. Also, the sorting using the OrderBy clause is in ascending order by default. A program that demonstrates the OrderBy clause in C# is given as follows: using System; using System.Linq; using System.Collections.Generic; public class Fruit { public string NAME { get; set; } } public class DEMO { public static void Main() { IList<Fruit> fruitList = new List<Fruit>() { new Fruit() { Name = "Orange" } , new Fruit() { Name = "Mango" } , new Fruit() { Name = "Apple" } , new Fruit() { Name = "Peach" } , new Fruit() { Name = "Guava" } , }; var sortAscendingOrder = from f in fruitList orderby f.Name select f; var sortDescendingOrder = from f in fruitList orderby f.Name descending select f; Console.WriteLine("Fruit Names in Ascending Order:"); foreach (var i in sortAscendingOrder) Console.WriteLine(i.Name); Console.WriteLine("\nFruit Names in Descending Order:"); foreach (var i in sortDescendingOrder) Console.WriteLine(i.Name); } }The output of the above program is given as follows: Fruit Names in Ascending Order: Apple Guava Mango Orange Peach Fruit Names in Descending Order: Peach Orange Mango Guava Apple |
|