C#のSortedDictionaryを逆方向(逆方向)に繰り返す方法はありますか?
または、最初にSortedDictionaryを降順で定義する方法はありますか?
C#のSortedDictionaryを逆方向(逆方向)に繰り返す方法はありますか?
または、最初にSortedDictionaryを降順で定義する方法はありますか?
SortedDictionary 自体は後方反復をサポートしていませんが、同じ効果を達成する可能性がいくつかあります。
.Reverse
-メソッド (Linq)を使用します。(これは、辞書出力全体を事前に計算する必要がありますが、最も簡単な解決策です)
var Rand = new Random();
var Dict = new SortedDictionary<int, string>();
for (int i = 1; i <= 10; ++i) {
var newItem = Rand.Next(1, 100);
Dict.Add(newItem, (newItem * newItem).ToString());
}
foreach (var x in Dict.Reverse()) {
Console.WriteLine("{0} -> {1}", x.Key, x.Value);
}
辞書を降順でソートします。
class DescendingComparer<T> : IComparer<T> where T : IComparable<T> {
public int Compare(T x, T y) {
return y.CompareTo(x);
}
}
// ...
var Dict = new SortedDictionary<int, string>(new DescendingComparer<int>());
SortedList<TKey, TValue>
代わりに使用してください。パフォーマンスはディクショナリ (O(logn) ではなく O(n)) ほどではありませんが、配列のように要素にランダム アクセスできます。汎用の IDictionary-Interface を使用すると、残りのコードを変更する必要がなくなります。
編集 :: SortedLists の繰り返し
インデックスで要素にアクセスするだけです!
var Rand = new Random();
var Dict = new SortedList<int, string>();
for (int i = 1; i <= 10; ++i) {
var newItem = Rand.Next(1, 100);
Dict.Add(newItem, (newItem * newItem).ToString());
}
// Reverse for loop (forr + tab)
for (int i = Dict.Count - 1; i >= 0; --i) {
Console.WriteLine("{0} -> {1}", Dict.Keys[i], Dict.Values[i]);
}
最初とは逆の順序で SortedDictionary を定義する最も簡単な方法は、IComparer<TKey>
通常とは逆の順序でソートする を指定することです。
MiscUtilからのいくつかのコードを次に示します。
using System.Collections.Generic;
namespace MiscUtil.Collections
{
/// <summary>
/// Implementation of IComparer{T} based on another one;
/// this simply reverses the original comparison.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class ReverseComparer<T> : IComparer<T>
{
readonly IComparer<T> originalComparer;
/// <summary>
/// Returns the original comparer; this can be useful
/// to avoid multiple reversals.
/// </summary>
public IComparer<T> OriginalComparer
{
get { return originalComparer; }
}
/// <summary>
/// Creates a new reversing comparer.
/// </summary>
/// <param name="original">The original comparer to
/// use for comparisons.</param>
public ReverseComparer(IComparer<T> original)
{
if (original == null)
{
throw new ArgumentNullException("original");
}
this.originalComparer = original;
}
/// <summary>
/// Returns the result of comparing the specified
/// values using the original
/// comparer, but reversing the order of comparison.
/// </summary>
public int Compare(T x, T y)
{
return originalComparer.Compare(y, x);
}
}
}
次に、次を使用します。
var dict = new SortedDictionary<string, int>
(new ReverseComparer<string>(StringComparer.InvariantCulture));
(または使用していたタイプ)。
一方向にのみ反復したい場合は、後で順序を逆にするよりも効率的です。
数値をキーとして扱う場合、ディクショナリを作成するときにそれらを単純に否定するという非常に単純なアプローチもあります。
.NET 3.5 を使用している場合は、OrderByDescending 拡張メソッドを使用できます。
var dictionary = new SortedDictionary<int, string>();
dictionary.Add(1, "One");
dictionary.Add(3, "Three");
dictionary.Add(2, "Two");
dictionary.Add(4, "Four");
var q = dictionary.OrderByDescending(kvp => kvp.Key);
foreach (var item in q)
{
Console.WriteLine(item.Key + " , " + item.Value);
}