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 actually rearranged anything? Bonus question: if it rearrange, how many things?
Taken from http://msdn.microsoft.com/en-us/library/bb348567.aspx You'd have to make a copy of the list before you sort it to compare it to, though.
List<Pet> pets1 = new List<Pet> { pet1, pet2 };
List<Pet> pets2 = new List<Pet> { pet1, pet2 };
bool equal = pets1.SequenceEqual(pets2);
Since you have implemented your own comparer, why not track 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 another approach, why not switch to sorted input rather than sorting 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 like SortedList<K,T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With