Posted By

fengelz on 12/05/10


Tagged

list sorting c#


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

cybermax
Priestd09
danfinrud55


Sorting generic list in C#


 / Published in: C#
 

One of those things in C# for which I always forget the syntax.

  1. //declare a class person
  2. class Person
  3. {
  4. public string Name;
  5. public Person(string name)
  6. {
  7. this.Name = name;
  8. }
  9. }
  10.  
  11. //create a list
  12. List<Person> persons = new List<Person>();
  13. persons.Add(new Person("Bernhard"));
  14. persons.Add(new Person("Adam"));
  15.  
  16.  
  17. //Writes out "Bernhard, Adam"
  18. foreach (Person p in persons)
  19. {
  20. Console.Write(p.Name+", ");
  21. }
  22.  
  23. //Sort the list by name ascending
  24. persons.Sort(delegate(Person a, Person b)
  25. {
  26. return a.Name.CompareTo(b.Name);
  27. });
  28.  
  29. //The sorted list now writes out "Adam, Bernhard"
  30. foreach (Person p in persons)
  31. {
  32. Console.Write(p.Name+", ");
  33. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Vordreller on December 5, 2010

Wait, how does this work?

Posted By: fengelz on February 1, 2011

Sorry Vordreller. I updated the snippet to hopefully make it more clear.

You need to login to post a comment.