Created
September 26, 2011 11:20
-
-
Save fengelz/1242038 to your computer and use it in GitHub Desktop.
Sorting generic list in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//declare a class person | |
class Person | |
{ | |
public string Name; | |
public Person(string name) | |
{ | |
this.Name = name; | |
} | |
} | |
//create a list | |
List<Person> persons = new List<Person>(); | |
persons.Add(new Person("Bernhard")); | |
persons.Add(new Person("Adam")); | |
//Writes out "Bernhard, Adam" | |
foreach (Person p in persons) | |
{ | |
Console.Write(p.Name+", "); | |
} | |
//Sort the list by name ascending | |
persons.Sort(delegate(Person a, Person b) | |
{ | |
return a.Name.CompareTo(b.Name); | |
}); | |
//The sorted list now writes out "Adam, Bernhard" | |
foreach (Person p in persons) | |
{ | |
Console.Write(p.Name+", "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment