Orderby clause in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 04-Sep-2018 08:05:14
Advertisements