c# List sorting code example

Example 1: c# how to sort a list

var simpleList = new List<ObjectName>();
// Order by a property
list.OrderBy(o => o.PropertyName);
// Order by multiple property
list.OrderBy(o => o.PropertyName).ThenBy(o => o.AnotherProperty);
// Same but descending
list.OrderByDescending(o => o.PropertyName).ThenByDescending(o => o.AnotherProperty);

Example 2: built in methods to order a list c#

using System.Linq;
//This list contains OrderDate, OrderID, Quantity, Total properties
List<Order> objListOrder = new List<Order>(); 
//How to GetOrderList(objListOrder)?
//Answer:
//- Ascending order
List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();
//- Descending order
List<Order> SortedList = objListOrder.OrderByDescending(o=>o.OrderDate).ToList();

Example 3: list sorting c#

using System.Linq;

//sorts in acending order {1,2,3,4,5}
myList.Sort();

//Sorts in decending order {5,4,3,2,1}
myList.Sort();
myList.Reverse();

//to sort a custom list of classes you have to 
//add this inside of your class
public int CompareTo(MyClass other)//replace MyClass with your class type
{
    //replace varInClass to the variable that you would like to compare
	return this.totalScore.CompareTo(other.varInClass)
}

Example 4: sort list in python

List_name.sort()
This will sort the given list in ascending order.

Example 5: c# sort list

using System;

class Program
{
    static void Main()
    {
        string[] colors = new string[]
        {
            "orange",
            "blue",
            "yellow",
            "aqua",
            "red"
        };
        // Call Array.Sort method.
        Array.Sort(colors);
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }
    }
}