sort a list in c# in csharp

To sort a List in C#, you can use the built-in List.Sort() method, which uses an implementation of the QuickSort algorithm. Here is an example:

main.cs
List<int> myList = new List<int> { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };

myList.Sort();

foreach (int num in myList)
{
    Console.Write(num + " ");
}
// Output: 1 1 2 3 3 4 5 5 5 6 9 
183 chars
10 lines

If you have a custom object that you want to sort based on a specific property, you can use the overload of List.Sort() that takes a Comparison<T> delegate. Here is an example:

main.cs
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> peopleList = new List<Person>
{
    new Person { Name = "Alice", Age = 25 },
    new Person { Name = "Bob", Age = 42 },
    new Person { Name = "Charlie", Age = 17 },
    new Person { Name = "Dave", Age = 32 }
};

peopleList.Sort((p1, p2) => p1.Name.CompareTo(p2.Name)); // Sort by Name

foreach (Person person in peopleList)
{
    Console.WriteLine(person.Name + " (" + person.Age + ")");
}
// Output: Alice (25) Bob (42) Charlie (17) Dave (32)
547 chars
22 lines

In this example, we sort the peopleList by the Name property of each Person object, using a lambda expression as the comparison function. You could also sort by Age, or any other property of the Person class.

gistlibby LogSnag