How can I sort generic list DESC and ASC?

Penguen picture Penguen · Jun 17, 2010 · Viewed 207.1k times · Source

How can I sort generic list DESC and ASC? With LINQ and without LINQ? I'm using VS2008.

class Program
{
    static void Main(string[] args)
    {
        List<int> li = new List<int>();

        li.Add(456);
        li.Add(123);
        li.Add(12345667);
        li.Add(0);
        li.Add(1);

        li.Sort();

        foreach (int item in li)
        {
            Console.WriteLine(item.ToString() + "\n");
        }

        Console.ReadKey();
    }
}

Answer

Anthony Pegram picture Anthony Pegram · Jun 17, 2010

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();