Gal*_*man 40 .net c# iteration reverse dictionary
有什么方法可以通过c#中的SortedDictionary向后(反向)迭代?
或者有没有办法以降序开始定义SortedDictionary?
Dar*_*rio 67
SortedDictionary本身不支持向后迭代,但您有几种可能性来实现相同的效果.
使用.Reverse-Method(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);
}
Run Code Online (Sandbox Code Playgroud)使字典按降序排序.
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>());
Run Code Online (Sandbox Code Playgroud)请SortedList<TKey, TValue>改用.性能不如字典(O(n)而不是O(logn)),但你可以像数组一样对元素进行随机访问.使用通用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]);
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 17
以相反的顺序定义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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你用:
var dict = new SortedDictionary<string, int>
(new ReverseComparer<string>(StringComparer.InvariantCulture));
Run Code Online (Sandbox Code Playgroud)
(或者你使用的任何类型).
如果您只想在一个方向上进行迭代,那么这比之后反转顺序更有效.
简单地在一行中创建一个反向排序的字典。
var dict = new SortedDictionary<int, int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
Run Code Online (Sandbox Code Playgroud)
有一种创建IComparer<T>using的方法System.Collections.Generic.Comparer<T>。只需将一个IComparision<T>委托传递给它的Create方法即可构建一个IComparer<T>。
var dict = new SortedDictionary<int, TValue>(
Comparer<int>.Create(
delegate(int x, int y)
{
return y.CompareTo(x);
}
)
);
Run Code Online (Sandbox Code Playgroud)
如果含义很重要,则可以使用lambda表达式 / 局部函数 / 方法替换委托(TKey, TKey) => int。