Home » c# » How can I sort generic list DESC and ASC?

How can I sort generic list DESC and ASC?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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();
    }
}
Answers:

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();

Questions:
Answers:

Without Linq:

Ascending:

li.Sort();

Descending:

li.Sort();
li.Reverse();

Questions:
Answers:

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

Questions:
Answers:

Very simple way to sort List with int values in Descending order:

li.Sort((a,b)=> b-a);

Hope that this helps!