How to check if List <T> .Sort was really sorted?
Consider the following code:
class Employee : IComparable<Employee> { public string Name { get; set; } public int CompareTo(Employee other) { return string.Compare(this.Name, other.Name); } } void DoStuff() { var e1 = new Employee() { Name = "Frank" }; var e2 = new Employee() { Name = "Rizzo" }; var lst = new List<Employee>() { e1, e2 }; lst.Sort(); } How do I know if the Sort method really rebuilt something? Bonus question: if it changes, how many things?
+4
3 answers
Taken from http://msdn.microsoft.com/en-us/library/bb348567.aspx You will need to make a copy of the list before sorting it to compare it with.
List<Pet> pets1 = new List<Pet> { pet1, pet2 }; List<Pet> pets2 = new List<Pet> { pet1, pet2 }; bool equal = pets1.SequenceEqual(pets2); +4
Since you implemented your own comparator, why not keep track of how many times it is called?
// naive, not thread safe, not exactly going to tell you much static int compared = 0; public int CompareTo(Employee other) { compared++; return string.Compare(this.Name, other.Name); } As a different approach, why not switch to sorted input rather than sort the entire list each time?
public void AddEmployee(Employee item) { // keep in mind this may not always be faster than List<T>.Sort // but it should be. if (employees.Count > 1) { var index = employees.BinarySearch(item); if (index < 0) { employees.Insert(~index, item); } } else employees.Add(item); } Alternatively, use a sorted collection, such as SortedList<K,T> .
+3
This may not seem like the best solution, but why not register the result of string.Compare
public int CompareTo(Employee other) { int result = string.Compare(this.Name, other.Name); Debug.WriteLine("Result of Compare of {0} and {1} is {2}", this.Name, other.Name, result); return result; } +2