How can I sort generic list DESC and ASC?

C#.NetLinq

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Without Linq:

Ascending:

li.Sort();

Descending:

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

Solution 3 - C#

without linq, use Sort() and then Reverse() it.

Solution 4 - C#

I was checking all the answer above and wanted to add one more additional information. I wanted to sort the list in DESC order and I was searching for the solution which is faster for bigger inputs and I was using this method earlier :-

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

but my test cases were failing for exceeding time limits, so below solution worked for me:-

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

So Ultimately the conclusion is that 2nd way of Sorting list in Descending order is bit faster than the previous one.

Solution 5 - C#

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

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

Hope that this helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionALEXALEXIYEVView Question on Stackoverflow
Solution 1 - C#Anthony PegramView Answer on Stackoverflow
Solution 2 - C#Sani Singh HuttunenView Answer on Stackoverflow
Solution 3 - C#Srinivas Reddy ThatiparthyView Answer on Stackoverflow
Solution 4 - C#sarawgeekView Answer on Stackoverflow
Solution 5 - C#Sunil MuraliView Answer on Stackoverflow