Sort an Array or a Collection - CSharp Collection

CSharp examples for Collection:List

Description

Sort an Array or a Collection

Demo Code

using System;//from ww  w.  j  av  a 2  s. co  m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class MainClass
{
   public static void Main()
   {
      int[] array = { 4, 2, 9, 3 };
      array = Enumerable.OrderBy(array, e => e).ToArray<int>();
      foreach (int i in array) {
         Console.WriteLine(i);
      }
      // create a list and populate it
      List<string> list = new List<string>();
      list.Add("K");
      list.Add("A");
      list.Add("M");
      list.Add("K");
      list.Add("A");
      list.Add("A");
      // enumerate the sorted contents of the list
      Console.WriteLine("\nList sorted by content");
      foreach (string person in Enumerable.OrderBy(list, e => e))
      {
         Console.WriteLine(person);
      }
      // sort and enumerate based on a property
      Console.WriteLine("\nList sorted by length property");
      foreach (string person in Enumerable.OrderBy(list, e => e.Length))
      {
         Console.WriteLine(person);
      }
      // Create a new ArrayList and populate it.
      ArrayList arraylist = new ArrayList(4);
      arraylist.Add("M");
      arraylist.Add("K");
      arraylist.Add("A");
      arraylist.Add("A");
      // Sort the ArrayList.
      arraylist.Sort();
      foreach (string s in list) {
         Console.WriteLine(s);
      }
   }
}

Result


Related Tutorials