LINQ OrderBy Query Operator

By Peter Bromberg

Sorts the elements of a sequence in ascending order. OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>) - Sorts the elements of a sequence in ascending order according to a key. OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>) - Sorts the elements of a sequence in ascending order by using a specified comparer.

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

             public static void OrderByEx1()
            {
                Pet[] pets = { new Pet { Name="Barley", Age=8 },
                               new Pet { Name="Boots", Age=4 },
                               new Pet { Name="Whiskers", Age=1 } };

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

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

            /*
             This code produces the following output:

             Whiskers - 1
             Boots - 4
             Barley - 8
             */


LINQ OrderBy Query Operator  (1333 Views)