C# sort list

To sort a list in ascending or desceding order, you can use sort method. By default, the sort method will sort the list in ascending order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Csharp_exercises
{

class Program
{


static void Main(string[] args)
{


  //create List object
  List<double> lst = new List<double>();
  Random rn = new Random();
  for (int i = 0; i < 10; i++)
  {

      lst.Add(rn.NextDouble());
   }

   lst.Sort(); //sort list in ascending order

  foreach (double v in lst)
   Console.WriteLine("{0:F}",v);


  Console.Read();

   }


  }
}

If you want to sort it in descending order you must define a method for comparison and supply this method to the sort method. In the example code below, i create a com(double x,double y) method to define the comparison rule. This method starts to compare one item to its next item. If it is less than its next item, return 1. If it is greater than its next item, return -1. If both are equal, return 0.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Csharp_exercises
{

class Program
{


static void Main(string[] args)
{
  //create List object
  List<double> lst = new List<double>();
   Random rn = new Random();
   for (int i = 0; i < 10; i++)
  {
     lst.Add(rn.NextDouble());
 }

    lst.Sort(com); //sort list in descending order

   foreach (double v in lst)
     Console.WriteLine("{0:F}",v);


  Console.Read();

}

private static int com(double x,double y)
{
   if (x < y) return 1;
   else if (x > y) return -1;
   else return 0;
  }
  }
}

Posted by: Dara | post date: 01-28-2013 | Subject: C# Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.