允许重复键的 C# 可排序集合

标签 c# .net collections sortedlist

我正在编写一个程序来设置各种对象在报告中出现的顺序。 该序列是 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/

相关文章:

java - 有没有办法检查 Stream 是否包含所有集合元素?

c# - 从长度为 M 的未排序数组中搜索前 N 个已排序整数?

c# - 升级到 .NET 4.7 后为 "Predefined type System.ValueTuple is not defined or imported"

c# - 添加自定义声明类型

c# - ASP.NET MVC 3 - 授权属性的不同登录页面

c# - 为什么 Tuple<T1...TRest> 中的 TRest 不受约束?

c# - 如何获取方法的 MethodBase 对象?

.net - VB 6/.NET 互操作最近是否被 Windows 更新破坏了?

java - while(true) 和集合

java - 此 java 对象是否符合 List 中的垃圾回收条件