C# Enumerable OrderBy(IEnumerable, Func)

Description

Sorts the elements of a sequence in ascending order according to a key.

Syntax


public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
  this IEnumerable<TSource> source,
  Func<TSource, TKey> keySelector
)

Parameters

  • TSource - The type of the elements of source.
  • TKey - The type of the key returned by keySelector.
  • source - A sequence of values to order.
  • keySelector - A function to extract a key from an element.

Example

The following code example demonstrates how to use OrderBy to sort the elements of a sequence.


/*from  www  . ja v a2 s .c o m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    Pet[] pets = { new Pet { Name="a", Age=8 },
                   new Pet { Name="b", Age=4 },
                   new Pet { Name="c", Age=1 } };

    IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);

    foreach (Pet pet in query)
    {
        Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
    }


  }
}
    
class Pet{
   public string Name { get; set; }
   public int Age { get; set; }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable