0

リストから削除するアイテムをnullとして設定し、IComparableメソッドCompareToを介してリストを並べ替えて、nullアイテムが一番上になるようにしています...次に、リストで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); でエラーが発生します。と言って:配列内の2つの要素を比較できませんでした

なんでそうなの??

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 に答える