我正在编写一个程序来设置各种对象在报告中出现的顺序。
该序列是 Excel 电子表格上的 Y 位置(单元格)。
代码的演示部分如下。
我想要完成的是拥有一个集合,这将允许我添加多个对象,并且我可以根据顺序获得排序的集合
SortedList list = new SortedList();
Header h = new Header();
h.XPos = 1;
h.name = "Header_1";
list.Add(h.XPos, h);
h = new Header();
h.XPos = 1;
h.name = "Header_2";
list.Add(h.XPos, h);
我知道SortedList
不会允许这样做,我一直在寻找替代方案。我不想排除重复的并且已经尝试过List<KeyValuePair<int, object>>
.
Thanks.
使用您自己的 IComparer!
就像其他一些答案中已经指出的那样,您应该使用自己的比较器类。为此,我使用通用的 IComparer 类,它可以与实现 IComparable 的任何对象一起使用:
/// <summary>
/// Comparer for comparing two keys, handling equality as beeing greater
/// Use this Comparer e.g. with SortedLists or SortedDictionaries, that don't allow duplicate keys
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class DuplicateKeyComparer<TKey>
:
IComparer<TKey> where TKey : IComparable
{
#region IComparer<TKey> Members
public int Compare(TKey x, TKey y)
{
int result = x.CompareTo(y);
if (result == 0)
return 1; // Handle equality as being greater. Note: this will break Remove(key) or
else // IndexOfKey(key) since the comparer never returns 0 to signal key equality
return result;
}
#endregion
}
您将在实例化新的 SortedList、SortedDictionary 等时使用它:
SortedList<int, MyValueClass> slist = new SortedList<int, MyValueClass>(new DuplicateKeyComparer<int>());
这里int是可以重复的key。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)