Orderby clause in C#


The orderby is used in C# to sort elements in the collection based on specified fields in a particular order. The order can be ascending or descending.

The following is our list with elements −

List<string> myList = new List<string>();

// adding elements
myList.Add("iOS by Apple");
myList.Add("Android by Google");
myList.Add("Symbian by Nokia");

Now, use Orderby to order the elements in descending order −

var myLen = from element in myList orderby element.Length descending select element;

The following is the complete code −

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("iOS by Apple");
      myList.Add("Android by Google");
      myList.Add("Symbian by Nokia");

      var myLen = from element in myList
      orderby element.Length descending
      select element;
      Console.WriteLine("Descending order...");

      foreach (string str in myLen) {
         Console.WriteLine(str);
      }
   }
}

Output

Descending order...
Android by Google
Symbian by Nokia
iOS by Apple

Updated on: 22-Jun-2020

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements