How to use LINQ to sort a list in C#?


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

 Live Demo

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements