[英]How to check whether List<T>.Sort actually sorted something?
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? 我怎么知道Sort方法是否实际上重新排列了什么? 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. 摘自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);
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>
. 或者,使用
SortedList<K,T>
等排序集合。
It might not sound as the nicest solution but why not log the result of string.Compare
它可能听起来不是最好的解决方案,但为什么不记录
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.