List 无法删除列表中的项目范围

List 无法删除列表中的项目范围,list,c#-4.0,sorting,generic-list,List,C# 4.0,Sorting,Generic List,我将要从列表中删除的项目设置为null,然后通过IComparable方法CompareTo对列表进行排序,以便null项目位于顶部。。。然后在列表上使用RemoveRange函数,但无法执行。。。我认为以下代码没有问题: try { foreach (Invoice item in inv) { if (item.qty == 0) { i

我将要从列表中删除的项目设置为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);
}
#区域i可比较成员
公共整数比较(发票其他)
{
将此.CustomerName.CompareTo返回(其他.CustomerName);
}
#端区
inv.RemoveRange(0,i)发生错误;说明:数组中两个元素比较失败

为什么会这样

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);
    }


null。与(null)
相比?哦,是的。。。那么,我该如何解决这个问题呢?排序方法是否会将空值的项放在列表的顶部?另外,{将此.qty.CompareTo(other.qty);}返回到item.qty=0;:)将执行此任务。。。谢谢。如果您的业务逻辑得到尊重,就去做;)
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);
        }