请考虑以下代码:
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();
}
我如何知道Sort方法是否实际重新安排了什么?奖金问题:如果它重新排列,有多少东西?
答案 0 :(得分:4)
摘自http://msdn.microsoft.com/en-us/library/bb348567.aspx但是,在对其进行排序以进行比较之前,您必须复制一份列表。
List<Pet> pets1 = new List<Pet> { pet1, pet2 };
List<Pet> pets2 = new List<Pet> { pet1, pet2 };
bool equal = pets1.SequenceEqual(pets2);
答案 1 :(得分:3)
由于您已经实现了自己的比较器,为什么不跟踪它被调用的次数?
// 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);
}
作为另一种方法,为什么不切换到排序输入而不是每次都对整个列表进行排序?
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);
}
或者,使用排序的集合,如SortedList<K,T>
。
答案 2 :(得分:2)
它可能听起来不是最好的解决方案,但为什么不记录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;
}