我将要从列表中删除的项目设置为null,然后通过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)发生错误;说:无法比较数组中的两个元素
为什么会这样?
答案 0 :(得分: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);
}