c#预订购泛型列表

本文关键字:泛型 列表 | 更新日期: 2023-09-27 18:09:15

我在c#中寻找一个排序列表,但是当我插入一个项目时,在插入所有后不排序。

SortedListDictionary都不合适,因为我可能有重复的密钥。

例如:

list.Insert(1001, v1);
list.Insert(1002, v2);
list.Insert(1002, v3);
list.Insert(1003, v4);

c#预订购泛型列表

一种可能性是编写一个自定义比较器,允许在集合中重复键:

public class DuplicateKeyComparer<TKey> : IComparer<TKey> where TKey : IComparable
{
    public int Compare(TKey x, TKey y)
    {
        var res = x.CompareTo(y);
        return res == 0 ? 1 : res;
    }
}

然后使用SortedList<TKey, TValue>:

var comparer = new DuplicateKeyComparer<int>();
var list = new SortedList<int, string>(comparer);
list.Add(1001, "v1");
list.Add(1002, "v2");
list.Add(1002, "v3");
list.Add(1003, "v4");

显然,这种方法有一些您应该注意的问题——您将永远无法从这个集合中删除任何键。因此,如果您打算使用list.Remove(1002)作为示例,那么您将需要另一种方法。