我正在编写一个程序来设置各种对象在报告中出现的顺序。 该序列是 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>>
.
谢谢。
最佳答案
使用您自己的 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。
关于允许重复键的 C# 可排序集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5716423/