code_junkie

I have a problem with IComparable and the collection sort method

Nov 14th, 2011
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. class Parent : IComparable<Parent>
  2. class Child : Parent
  3.  
  4. Child a = new Child();
  5. Child b = new Child();
  6. a.CompareTo(b);
  7.  
  8. List<Child> l = new List<Child>();
  9. l.Add(b);
  10. l.Add(a);
  11. l.Sort();
  12.  
  13. public int CompareTo(IDType other)
  14. {
  15. return this.Name.ToString().CompareTo(other.ToString());
  16. }
  17.  
  18. public class Parent : IComparable<Parent>
  19. {
  20. public int Age { get; set; }
  21.  
  22.  
  23. public int CompareTo(Parent other)
  24. {
  25.  
  26. return this.Age.CompareTo(other.Age);
  27. }
  28.  
  29. }
  30.  
  31. public class Child : Parent
  32. {
  33. public string Name { get; set; }
  34. }
  35.  
  36. public class Parent : IComparable
  37. {
  38. public int Age { get; set; }
  39.  
  40.  
  41. public int CompareTo(object other)
  42. {
  43. Parent p = other as Parent;
  44. return this.Age.CompareTo(p.Age);
  45. }
  46.  
  47. }
  48.  
  49. public class Child : Parent
  50. {
  51. public string Name { get; set; }
  52. }
  53.  
  54. List<Child> c = new List<Child>();
  55. c.Add(new Child { Age = 10, Name = "Alex" });
  56. c.Add(new Child { Age = 6, Name = "Jack" });
  57. c.Add(new Child { Age = 15, Name = "Bob" });
  58.  
  59. c.Sort();
Add Comment
Please, Sign In to add comment