代码

public class Cost

{

public double cost;

public int id;

}


public class CostComparer : IComparer<Cost>

{

public int Compare(Cost x, Cost y)

{

if (x.cost - y.cost < 1e-10)

{

return -1;

}

else

{

return 1;

}

}

}



错误的写法:

SortedList<double> list = new SortedList<double>(new CostComparer());\\XX

SortedList<double, Cost> list = new SortedList<double, Cost>(new CostComparer());\\XX

错误提示:

非泛型 类型“System.Collections.SortedList”不能与类型实参一起使用


可行的写法,浪费存储空间,SortedList并没有提供直接根据索引访问集合元素的方法,所以只能够通过其他的方法访问:

SortedList<Cost, Cost> list = new SortedList<Cost, Cost>(new CostComparer());


Cost c1 = new Cost();

c1.cost = 20;

c1.id = 30;

list.Add(c1, c1);


Cost c2 = new Cost();

c2.cost = 10;

c2.id = 40;

list.Add(c2, c2);

//方法一GetEnumerator

IEnumerator<KeyValuePair<Cost, Cost>> iter = list.GetEnumerator();

iter.MoveNext();

Cost tmpKey = iter.Current.Key;

Cost tmpValue = iter.Current.Value;


//方法二foreach

foreach (KeyValuePair<Cost, Cost> t in list)

{

Cost tmpKey = t.Key;

Cost tmpValue = t.Value;

}


删除某个索引键值对: list.RemoveAt(0);


但是为了简单起见,实际上,只是对Cost中的cost字段进行排序,并且支持重复插入,可以使用SortedSet

SortedSet<Cost> set = new SortedSet<Cost>(new CostComparer());\\OK