CSharp - LINQ OrderBy

Introduction

The OrderBy operator sorts an input sequence based on a keySelector method that will return a key value for each input element.

An ordered output sequence, IOrderedEnumerable<T>, will be yielded in ascending order based on the values of the returned keys.

The sort performed by the OrderBy operator is unstable.

The order of two input elements with the same with value are not reversed or maintained.

Prototypes

The OrderBy operator has two prototypes we will cover.

The First OrderBy Prototype

public static IOrderedEnumerable<T> OrderBy<T, K>(
         this IEnumerable<T> source,
         Func<T, K> keySelector)
       where
         K : IComparable<K>;

In this prototype of OrderBy, an input source sequence is passed into the OrderBy operator along with a keySelector method delegate.

An object is returned that, when enumerated, enumerates the source input sequence in order.

The keySelector method is passed an input element of type T and will return the field within the element that is to be used as the key value, of type K.

Types T and K may be the same or different types.

The type of the value returned by the keySelector method must implement the IComparable interface.

The Second OrderBy Prototype

public static IOrderedEnumerable<T> OrderBy<T, K>(
         this IEnumerable<T> source,
         Func<T, K> keySelector,
         IComparer<K> comparer);

This prototype accepts a comparer object.

If this version of the OrderBy operator does not require that type K implement the IComparable interface.

Exceptions

ArgumentNullException is thrown if any arguments are null.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program// w w w . j a va2  s .  c o m
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        IEnumerable<string> items = codeNames.OrderBy(s => s.Length);
        
        foreach (string item in items)
            Console.WriteLine(item);

    }
}

Result

Related Topics