Musings
Public · Protected · Private
IComparable,IComparer
-
2012-06-14 02:39public interface IComparable { int CompareTo(object o); } so class Human { public string Name{get;set;} public Human(string name) { Name = name; } } will change as class Human : IComparer { public string Name { get; set; } public Human(string name) { Name = name; } int IComparer.Compare(object o1, object o2) { Human t1 = o1 as Human; Human t2 = o2 as Human; if (t1 != null && t2 != null) return String.Compare(t1.Name, t2.Name); else throw new ArgumentException("Parameter is not a Human!"); } }
-
2012-06-14 02:55Other ways of comparing public class HumanNameComaparer : IComparer { // Test the pet name of each object. int IComparer.Compare(object o1, object o2) { Human t1 = o1 as Human; Human t2 = o2 as Human; if (t1 != null && t2 != null) return String.Compare(t1.Name, t2.Name); else throw new ArgumentException("Parameter is not a Human!"); } } public class HumanNameSizeComaparer : IComparer { // Test the pet name of each object. int IComparer.Compare(object o1, object o2) { Human t1 = o1 as Human; Human t2 = o2 as Human; if (t1 != null && t2 != null) return (t1.Name.Length>t2.Name.Length)? 1 : -1; else throw new ArgumentException("Parameter is not a Human!"); } }
-
2012-06-14 02:56now we can do ... class staff : IEnumerable { private Human[] employees = new Human[4]; public staff() { employees[0] = new Human("bob"); employees[1] = new Human("chris"); employees[2] = new Human("jennifer"); employees[3] = new Human("Brian"); } public void donamesort() { //Array.Sort(employees); Array.Sort(employees, new HumanNameComaparer()); } public void donameSizesort() { //Array.Sort(employees); Array.Sort(employees, new HumanNameSizeComaparer()); } public IEnumerator GetEnumerator() { foreach (Human c in employees) { yield return c; } } }
-
2012-06-14 02:56staff y = new staff(); foreach (Human h in y) { MessageBox.Show(h.Name); } y.donamesort(); foreach (Human h in y) { MessageBox.Show(h.Name); } y.donameSizesort(); foreach (Human h in y) { MessageBox.Show(h.Name); }
This blog is frozen. No new comments or edits allowed.