Use the orderby leyword to sort a list in ascending or descending order.
The following is the list −
List<string> myList = new List<string>();
myList.Add("truck");
myList.Add("bus");
myList.Add("bicycle");
myList.Add("motorbike");Now let us sort the list in descending order −
myLen = from element in myList orderby element.Length descending select element;
Here is the complete code −
Example
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<string> myList = new List<string>();
myList.Add("truck");
myList.Add("bus");
myList.Add("bicycle");
myList.Add("motorbike");
var myLen = from element in myList
orderby element.Length
select element;
Console.WriteLine("Ascending order...");
foreach (string str in myLen){
Console.WriteLine(str);
}
myLen = from element in myList
orderby element.Length descending
select element;
Console.WriteLine("Descending order...");
foreach (string str in myLen) {
Console.WriteLine(str);
}
}
}Output
Ascending order... bus truck bicycle motorbike Descending order... motorbike bicycle truck bus