【问题标题】:unable to remove range of items in a list无法删除列表中的项目范围
【发布时间】:2012-06-11 08:52:22
【问题描述】:

我将要从列表中删除的项目设置为 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);说:无法比较数组中的两个元素

为什么会这样??

【问题讨论】:

  • null.CompareTo(null) ?
  • 哦,是的! ...那我该如何解决这个问题呢?
  • 排序方法不会把 null 的项目放在列表的顶部吗?

标签: list c#-4.0 sorting generic-list


【解决方案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);
        }

【讨论】:

  • 另外,{ return this.qty.CompareTo(other.qty);如果 item.qty=0; } 会做这个任务:) ...谢谢
  • 是的。如果您的业务逻辑受到尊重,那就去做吧;)
猜你喜欢
  • 2017-08-22
  • 2022-01-08
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多