使 SortList 实现重复键排序
SortList 默认对按Key来排序,且Key值不能重复,但有时可能需要用有重复值的Key来排序,以下是实现方式:
1、对强类型:以float为例
#region 使SortList能对重复键排序
internal class ListComparer : IComparer<float>
{
static private ListComparer mono;
public static ListComparer EarlyFirst
{
get
{
if (mono == null)
mono = new ListComparer();
return mono;
}
}
#region IComparer 成员
public int Compare(float x, float y)
{
if (x == y)
return -1;
else if (x < y)
return -1;
else
return 1;
}
#endregion
}
internal class CList : SortedList<float, int>
{
public CList()
:base(ListComparer.EarlyFirst)
{
}
}
#endregion
用法:直接用CList类代替SortedList类
2、对非强类型:
首先要实现IComparer接口
internal class ListComparer : IComparer
{
#region IComparer 成员
public int Compare(object x, object y)
{
//return -1;//不排序
//排序
int iResult = (int)x - (int)y;
if(iResult == 0) iResult = -1;
return iResult;
}
#endregion
}
用法:
SortList st=new SortList(new ListComparer());
st.add(11,23);
st.add(22,23);
st.add(11,23);
输出结果是11,11,22