Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fengelz
Created September 26, 2011 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fengelz/1242038 to your computer and use it in GitHub Desktop.
Save fengelz/1242038 to your computer and use it in GitHub Desktop.
Sorting generic list in C#
//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