以下から派生する独自のクラスを作成できますSortedSet
。
public class SortedTupleBag<TKey, TValue> : SortedSet<Tuple<TKey, TValue>>
where TKey : IComparable
{
private class TupleComparer : Comparer<Tuple<TKey, TValue>>
{
public override int Compare(Tuple<TKey, TValue> x, Tuple<TKey, TValue> y)
{
if (x == null || y == null) return 0;
// If the keys are the same we don't care about the order.
// Return 1 so that duplicates are not ignored.
return x.Item1.Equals(y.Item1)
? 1
: Comparer<TKey>.Default.Compare(x.Item1, y.Item1);
}
}
public SortedTupleBag() : base(new TupleComparer()) { }
public void Add(TKey key, TValue value)
{
Add(new Tuple<TKey, TValue>(key, value));
}
}
コンソールアプリでの使用法:
private static void Main(string[] args)
{
var tuples = new SortedTupleBag<decimal, string>
{
{2.94M, "Item A"},
{9.23M, "Item B"},
{2.94M, "Item C"},
{1.83M, "Item D"}
};
foreach (var tuple in tuples)
{
Console.WriteLine("{0} {1}", tuple.Item1, tuple.Item2);
}
Console.ReadKey();
}
この結果を生成します:
1.83 Item D
2.94 Item A
2.94 Item C
9.23 Item B