c# sorting code example

Example 1: 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 2: 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 3: array sort c#

Array.Sort(myArray);

Example 4: c# sort array

Array.Sort(arr);

Example 5: c# sort array

int[] sortedCopy = from element in copyArray 
                    orderby element ascending select element;

Example 6: sorting array in c#

int[] arr = { 3, 6, 4, 1 };

// arr will be { 1, 3, 4, 6 }
Array.Sort(arr);

// arr will be { 6, 4, 3, 1 }
Array.Sort(arr);
Array.Reverse(arr);