Use the LINQ orderby keyword to sort a list in C#.
In the below example, we have set the orderby for the elements −
var myLen = from element in myList orderby element.Length select element;
Let us see an example −
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("cab");
myList.Add("motorbike");
var myLen = from element in myList
orderby element.Length
select element;
foreach (string str in myLen) {
Console.WriteLine(str);
}
}
}The above will produce the following result. The word with less number of characters will be displayed first like an ascending order list −
Output
bus cab truck motorbike