4

考虑以下代码:

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 方法是否真的重新排列了任何东西?额外的问题:如果重新排列,有多少东西?

4

3 回答 3

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);
于 2013-03-01T23:04:31.307 回答
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>.

于 2013-03-01T23:11:29.547 回答
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;
}
于 2013-03-01T23:08:47.873 回答