0

我正在将要从列表中删除的项目设置为空,然后通过 IComparable 方法 CompareTo 对列表进行排序,以便空项目位于顶部......然后在列表上使用 RemoveRange 函数但无法如此......我明白了以下代码没有问题:

      try
      {
          foreach (Invoice item in inv)
          {
              if (item.qty == 0)
              {
                  item.CustomerName = null;
                  item.qty = 0;
                  i++;
              }
          }
          inv.Sort();
          inv.RemoveRange(0, i);
      }
      catch (Exception ex)
      {
          Console.WriteLine(ex.Message);

}

        #region IComparable<Invoice> Members

    public int CompareTo(Invoice other)
    {
        return this.CustomerName.CompareTo(other.CustomerName);
    }

    #endregion

错误发生在 inv.RemoveRange(0,i); 说:无法比较数组中的两个元素

为什么会这样??

4

1 回答 1

1
public int CompareTo(Invoice other)
    {
    if (other == null || other.CustomerName == null) return 1;
    if (this.CustomerName == null) return -1;

    return this.CustomerName.CompareTo(other.CustomerName);
    }

或者

public int CompareTo(Invoice other)
        {
        //if other Invoide is null, instance is bigger.
        if (other == null) return 1;
        if (this.CustomerName == null) {
           //if both CustomerName are null, instance equals other. Of only instance CustomerName is null, other is bigger.
           return other.CustomerName == null ? 0 : -1;
        }
        //if other.CustomerName is null (and instance.CustomerName is not null), instance is bigger.
        if (other.CustomerName == null) return 1;

        //both CustomerName are not null, call basic string.CompareTo
        return this.CustomerName.CompareTo(other.CustomerName);
        }
于 2012-06-11T08:58:10.560 回答