views:

58

answers:

4

How can I sort DESC and ASC in a generic list? With LINQ and without LINQ ? I'm using vs 2008.

   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();
        }
    }
+5  A: 

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) => -1* a.CompareTo(b)); // 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();
Anthony Pegram
+1  A: 

with out linq, use Sort() and then Reverse() it.

Srinivas Reddy Thatiparthy
+1  A: 

Without Linq:

Ascending:

li.Sort();

Descending:

li.Sort();
li.Reverse();
Sani Huttunen
`Sort()` is a void method, so you can't chain the `Reverse()` to it in this manner. You'll need 2 separate operations. However, with LINQ you could chain it to an `OrderBy` but at that point you should just use `OrderByDescending` instead.
Ahmad Mageed
@Ahmad Mageed. Ofcourse... Late afternoon meltdown... :(
Sani Huttunen
A: 

You can implement Comparison method. http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

ZEAXIF