我正在寻找 C# 中的排序列表,但是当我插入一个项目时,在全部插入后未排序。
SortedList
和 Dictionary
都不适合,因为我可能有重复的键。
例如:
list.Insert(1001, v1);
list.Insert(1002, v2);
list.Insert(1002, v3);
list.Insert(1003, v4);
最佳答案
一种可能性是编写一个自定义比较器,它允许集合中出现重复的键:
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");
显然,您应该注意这种方法的罪魁祸首 - 您将永远无法从此集合中删除任何 key 。因此,如果您打算使用 list.Remove(1002)
例如,那么您将需要一种替代方法。
关于c# - 预购通用列表 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32167965/